The Command Design Pattern

What is it and how can we apply it?

Carlos Caballero
Dec 5, 2019 · 7 min read
Photo by Caspar Camille Rubin on Unsplash

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 class is declared as an interface for executing operations. This class defines a method, named , which must be implemented in each concrete command. This method is a bridge between a object and an action. The knows how to perform the operations associated with a request (any class may be a ). Another relevant component in this pattern is the 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 class 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

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 which defines the attributes: ; and an operation . This class is the bridge between client/context and the . The method is responsible for deciding what action should be executed. For example, if the is or the method should invoke the action in the . The following UML diagram shows the scenario that I’ve just described.

Here are the and codes:

The most relevant code smell is the method which is coupled to the actions/commands from . There are different techniques to avoid this code smell. In this case, the pattern is a good solution, since we want to log the command's history.

Finally, here is the class:

Here is the result:


Stockmarket Problem: Solution

The idea to decouple the commands from the 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 abstract class, which will have an abstract method called . This method will be invoked from the class (the invoker). Furthermore, 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 class will no longer receive a primitive attribute as a parameter (string) since this has no semantic value. Instead, the 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 receives the using DI (Dependency Injection). The invokes the command using the method, which performs the operation by the method.

Here’s the code associated with the :

You may note that the control structure is avoided by using the method, which delegates the responsibility to each command.

Here is the code associated with the and each order:

The class is not modified in this command. Following these modifications in the execution of the program, here is the result:



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: , and , two services: and and an agent: .

The Agent invokes the orders using the 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 method, and stored using the data-structure. Finally, the 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.

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.


Better Programming

Advice for programmers.

Thanks to Zack Shapiro

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!

Better Programming

Advice for programmers.

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