Command

Command

Behavioral pattern

The Command design pattern allows us to execute operations without having to know how they are implemented. These operations are known as commands, and each operation is implemented as an independent class performing a very specific action, which may or may not receive parameters in order to carry out its task. One of the advantages offered by this pattern is the ability to create as many commands as we need and encapsulate them into an execution interface.

Command design pattern structure.
Command design pattern structure.

The elements included in the Command pattern are:

  • ICommand: Interface describing the structure of the commands, which defines the generic execution method for all of them.
  • Concrete Command: They represent the concrete commands inheriting from ICommand. Each of these classes represents a command that can be executed independently.
  • Command Manager: This component lets us manage all the commands available at runtime, from here we're able to request commands or create new ones.
  • Invoker: It represents the action triggering one of the commands.
Command design pattern sequence diagram.
Command design pattern sequence diagram.
  1. The invoker gets a command from CommandManager.
  2. The invoker executes the command.
  3. The invoker gets another command from CommandManager.
  4. The invoker executes the command.

Real-world example

By implementing the Command design pattern, we are going to learn how to create our own, entirely functional, console by developing a series of commands that will be available for its use during the execution of the application.

Discover how the Command design pattern can help us solve this problem.
Discover how the Command design pattern can help us solve this problem.

About this book

Introducción a la arquitectura de software

Everything you just saw in this article is only a small part of the book Introduction to design patterns, the most complete book of design patterns in Spanish, we cover 25 design patterns along with 25 real-world projects. Forget about learning design patterns with typical Internet examples of how to make pizza, animals, and geometric shapes. I invite you to see my book:

See book
All rights reserved ©