Design Patterns: Command

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 the software development.

In this article, I am going to describe the how the Command Pattern; and how and when it should be applied.

Command Pattern: 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. The 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.

The UML diagram for this pattern is the following one:

Image for post
Image for post

The Command Pattern should be used when:

  1. You need a command to have a life span independent of the original request. Furthermore, if you want to queue, specify and execute requests at different times.
  2. You need undo/redo operations. The command’s execution can be stored for reversing its effects. It is important that the Command class implements the methods undo and redo.
  3. 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.

I will now show you how you can implement this pattern using JavaScript/TypeScript. In our case, I have made up a problem in which there is a class named Agent which defines the attributes: stockTrade; and an operation placeOrder. This class is the bridge between client/context and the StockTrader. The placeOrder method is responsible for deciding what action should to be executed. For example, if the orderType is buy or sell the method should invoke the action in the StockTrader. The following UML diagram shows the scenario that I have just described.

Image for post
Image for post

The client and Agent codes are the following ones:

Image for post
Image for post

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, the StockTrade class is the following one:

Image for post
Image for post

The result obtained is shown in the following image:

Image for post
Image for post

Command pattern — Example 1: A Stock Market — 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 which allows us to execute the action depending on each concrete command.

That is the reason why we have created the Order abstract class which will have an abstract method called execute. This method is the one that 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:

Image for post
Image for post

The code associate to the client is the following one:

Image for post
Image for post

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 though the execute method.

The code associated with the Agent is the following one:

Image for post
Image for post

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.

The code associated to the Order and each order are the following ones:

Image for post
Image for post
Image for post
Image for post
Image for post
Image for post

The StockTrade class is not modified in this command. So, the result after these modifications in the execution of the program is shown in the following image:

npm run example1-problem
npm run example1-command-solution1

Image for post
Image for post

Another interesting example which is resolved using 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. In the following UML diagram you can see this situation:

Image for post
Image for post

The code associated to the clients is the following:

Image for post
Image for post

In this example, there are three commands (saveSecretCommand, cleanCommand and moveCommand), two services (StoreService and R2D2Service) and an Agent (R2D2).

The Agent invokes the orders using the executeCommand method which receives two arguments: 1) The command; 2) The parameters to carry out the previous command.

Therefore, the code associated to the R2D2 is the following one:

Image for post
Image for post

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 to the command (abstract class) and each concrete command:

Image for post
Image for post

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.

Image for post
Image for post

The result obtained is shown in the following image:

Image for post
Image for post

I have created a npm scripts that run the example shown here after applying the command pattern.

npm run example2-command-solution-1

The command pattern can avoid complexity in your projects because you encapsules the commands in specific class which can be added/removed or changed in any moment (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 said pattern. This is crucial, since 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


Originally published at https://www.carloscaballero.io on May 23, 2019.

HackerNoon.com

#BlackLivesMatter

Sign up for UNSUBSCRIBE YOURSELF FROM THIS NEWSLETTER

By HackerNoon.com

how hackers start their afternoons. the real shit is on hackernoon.com. Take a look

Create a free Medium account to get UNSUBSCRIBE YOURSELF FROM THIS NEWSLETTER in your inbox.

Unlisted

Carlos Caballero

Written by

Hi! My name is Carlos Caballero and I’m PhD. in Computer Science from Málaga, Spain. Teaching developers and degree/master computer science how to be experts!

HackerNoon.com

Elijah McClain, George Floyd, Eric Garner, Breonna Taylor, Ahmaud Arbery, Michael Brown, Oscar Grant, Atatiana Jefferson, Tamir Rice, Bettie Jones, Botham Jean

Carlos Caballero

Written by

Hi! My name is Carlos Caballero and I’m PhD. in Computer Science from Málaga, Spain. Teaching developers and degree/master computer science how to be experts!

HackerNoon.com

Elijah McClain, George Floyd, Eric Garner, Breonna Taylor, Ahmaud Arbery, Michael Brown, Oscar Grant, Atatiana Jefferson, Tamir Rice, Bettie Jones, Botham Jean

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store