Understanding Design Patterns: Command Pattern using StockTrader and R2D2 (StarWars) Examples!
Tags: javascript, typescript, patterndesign, cleancode
Published: 2019-05-23 15:12:36

---
title: Understanding Design Patterns: Command Pattern using StockTrader and R2D2 (StarWars) Examples!
series: pattern-design
published: true
description: In this article, I am going to describe the how the **Command Pattern; and** how and when it should be applied.
tags: javascript, typescript, pattern-design, clean-code
canonical_url: https://www.carloscaballero.io/design-patterns-command
cover_image: https://cdn-images-1.medium.com/max/1000/1*DN02Yh1E9Kf1qTEvXD2R2w.jpeg
---

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:

![](https://cdn-images-1.medium.com/max/2000/0*whyKeG0cDMnC6thc.png)

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.

![](https://cdn-images-1.medium.com/max/2000/0*vHK1Rb4XuwtLAp2z.jpg)

The client and Agent codes are the following ones:

![](https://cdn-images-1.medium.com/max/3080/1*WhSV8UxGhu1OtdqN2gaQ-w.png)

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:

![](https://cdn-images-1.medium.com/max/2200/1*fRyDmFpm5m6w4HabCCFM3g.png)

The result obtained is shown in the following image:

![](https://cdn-images-1.medium.com/max/2558/0*doeDSU0BLE7UJK1R.png)

## 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:

![](https://cdn-images-1.medium.com/max/2000/0*I86O_Ct15YukrUH4.jpg)

The code associate to the client is the following one:

![](https://cdn-images-1.medium.com/max/2472/1*peJVrdECbOi6eWIijzavYg.png)

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:

![](https://cdn-images-1.medium.com/max/3380/1*48q9wNhns-YRtvCEtJj9MQ.png)

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:

![](https://cdn-images-1.medium.com/max/2776/1*fbHPcbMJcl_oFZegee425A.png)

![](https://cdn-images-1.medium.com/max/2400/1*URjsIe_7NW3m68_UyhtcZw.png)

![](https://cdn-images-1.medium.com/max/2400/1*pZlRXJFVCQRanr451jXn1Q.png)

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

![](https://cdn-images-1.medium.com/max/1000/1*DN02Yh1E9Kf1qTEvXD2R2w.jpeg)

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:

![](https://cdn-images-1.medium.com/max/2000/0*6PwzeJ_Tpi7J_eHf.jpg)

The code associated to the clients is the following:

![](https://cdn-images-1.medium.com/max/3212/1*sN2wHLJBfUwPV52YmY5IBQ.png)

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:

![](https://cdn-images-1.medium.com/max/2740/1*cak_eABVREn6dy9U6ZXHHA.png)

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:

![](https://cdn-images-1.medium.com/max/2808/1*FJMyGFs5kTh87PJZ4bFSFQ.png)

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.

![](https://cdn-images-1.medium.com/max/2704/1*WezAe4sDM84BnyhysLov6A.png)

The result obtained is shown in the following image:

![](https://cdn-images-1.medium.com/max/2236/0*J64_YrQG-KW3x5g9.png)

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](https://github.com/Caballerog/blog/tree/master/command-pattern)

*Originally published at [https://www.carloscaballero.io](https://www.carloscaballer.io/design-patterns-command) on May 23, 2019.*