The Command Design Pattern
What is it and how can we apply it?
There are 23 classic design patterns, which are described in the original book, Design Patterns: Elements of Reusable Object-Oriented Software. These patterns provide solutions to particular problems, often repeated in software development.
In this piece, I will describe the command pattern, and how and when it should be applied.
Command Pattern: The Basic Idea
In object-oriented programming, the command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time. This information includes the method name, the object that owns the method and values for the method parameters — Wikipedia
Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations
Design Patterns: Elements of Reusable Object-Oriented Software
In this pattern, an abstract
Command class is declared as an interface for executing operations. This
Command class defines a method, named
execute, which must be implemented in each concrete command. This
execute method is a bridge between a
Receiver object and an action. The
Receiver knows how to perform the operations associated with a request (any class may be a
Receiver). Another relevant component in this pattern is the
Invoker class, which asks for the command that must be executed.
Here is the UML diagram for this pattern:
The command pattern should be used when:
- You need a command to have a life span independent of the original request, or if you want to queue, specify and execute requests at different times.
- You need undo/redo operations. The command’s execution can be stored for reversing its effects. It is important that the
Commandclass implements the methods undo and redo.
- You need to structure a system around high-level operations built on primitive operations.
The command pattern has several advantages, summarised in the following points:
- It decouples the classes that invoke the operation from the object that knows how to execute the operation.
- It allows you to create a sequence of commands by providing a queue system.
- Implementing extensions to add a new command is easy and can be done without changing the existing code.
- You can also define a rollback system with the Command pattern — like in the Wizard example, we could write a rollback method.
- Have strict control over how and when commands are invoked.
- The code is easier to use, understand and test since the commands simplify the code.
Problem: A Stockmarket
Agent which defines the attributes:
stockTrade; and an operation
placeOrder. This class is the bridge between client/context and the
placeOrder method is responsible for deciding what action should be executed. For example, if the
sell the method should invoke the action in the
StockTrader. The following UML diagram shows the scenario that I’ve just described.
Here are the
The most relevant code smell is the
placeOrder method which is coupled to the actions/commands from
StockTrade. There are different techniques to avoid this code smell. In this case, the
Command pattern is a good solution, since we want to log the command's history.
Finally, here is the
Here is the result:
Stockmarket Problem: Solution
The idea to decouple the commands from the
Agent class is to create a set of classes for each command. However, the commands share a common interface that allows us to execute the action depending on each concrete command.
That is why we have created the
Order abstract class, which will have an abstract method called
execute. This method will be invoked from the
Agent class (the invoker). Furthermore,
Agent class will have a list of commands to obtain the command's history.
This way, the agent delegates the responsibility of knowing which operation has to be executed on the object it receives. The main change is that
Agent class will no longer receive a primitive attribute as a parameter (string) since this has no semantic value. Instead, the
Agent class will now receive a command object as a parameter, which provides semantic value.
The new UML diagram using the command pattern is shown below:
Here’s the code associated with the
In this case each
order receives the
StockTrade using DI (Dependency Injection). The
Agent invokes the command using the
placeOrder method, which performs the operation by the
Here’s the code associated with the
You may note that the
if-elseif-else control structure is avoided by using the
order.execute method, which delegates the responsibility to each command.
Here is the code associated with the
Order and each order:
StockTrade class is not modified in this command. Following these modifications in the execution of the program, here is the result:
npm run example1-problem
npm run example1-command-solution1
Example: A robot — R2D2
Another interesting example that is resolved using the command pattern is when there are several commands to execute for a robot.
For example, a set of commands as SaveSecret, Clean and Move are asked to a famous robot, R2D2. You can see this in the following UML diagram:
This is the code associated with the clients:
In this example, there are three commands:
moveCommand, two services:
R2D2Service and an agent:
The Agent invokes the orders using the
executeCommand method, which receives two arguments: the command and the parameters to carry out the previous command.
So, this is the code associated with the R2D2:
R2D2 has a list of commands, which may be listed through the
listCommands method, and stored using the
commands data-structure. Finally, the
executeCommand method is responsible for invoking the execute method of each command.
So, the next step is to create the code associated with the command (abstract class) and each concrete command:
Finally, each command invokes the service responsible for the action. In this case, we have used two different services to show that not all the commands delegate responsibility to the same service or class.
This is the result:
I’ve created an npm script that runs the example here, after applying the command pattern.
npm run example2-command-solution-1
The command pattern can help you to avoid complexity in your projects because you encapsulate the commands in a specific class which can be added/removed or changed at any time, including execution-time.
The most important thing is not implementing the pattern as I have shown you, but to be able to recognise the problem which this specific pattern can resolve, and when you may or may not implement the said pattern. This is crucial since the implementation will vary depending on the programming language you use.
The GitHub branch of this post is https://github.com/Caballerog/blog/tree/master/command-pattern