Beginner’s Guide to Command Design Pattern (Java)

Neha Gupta
6 min readJun 16, 2023

--

Hey reader 👋

In this blog we are going to take our Design Patterns further and are going to study about Command Design Pattern . In this blog we are going to study about its basic definition , implementation , advantages and real world examples .

Command Design Pattern : Definition

As the name suggests it is something related to commands given to system and the way they are controlled and executed . Command Pattern is one of the Behavioral Design Pattern. It is used to implement loose coupling in a request-response model.

The Command design pattern is a behavioral design pattern that aims to encapsulate a request as an object, thus allowing clients to parameterize and queue operations, as well as support undoable operations.

It decouples the sender of a request from the receiver, providing a way to issue commands without knowing the specific operation that will be performed or the receiver of the request.

To understand it in easy way let’s take an example suppose you are living in an automated house in which with the help of a remote controller you can turn on lights , AC , speaker , TV etc. So you are someone who invokes/generates a command with the help of remote controller now this command from remote controller goes to the system from which you are willing to get output , and this is how command execution takes place . Now here you as a client or sender of request is completely unaware of how this command is being executed , this is something that we can implement using Command Design Pattern. It also takes care of how these commands are executed in order they are given .

Components of Command Design Pattern

  1. Command: This is the core interface that declares the execution method. It typically includes a single method, such as execute(), which encapsulates the action to be performed.
  2. Concrete Command: This class implements the Command interface and represents a specific command. It contains a reference to the receiver (the object that will perform the action) and implements the execute() method by invoking the corresponding operation on the receiver.
  3. Receiver: The Receiver class defines the object that will perform the actual action requested by the command. It contains the necessary logic and functionality to carry out the operation. This can also be defined as Executer .
  4. Controller: This class is responsible for controlling the commands. It receives the command object, usually through a setter method, and triggers the execution of the command when required.
  5. Invoker :The Invoker creates the command objects, sets their receivers (if necessary), and assigns them to the controller. It is responsible for initiating requests .

Implementation of Command Design Pattern

To implement Command design pattern let’s use above example .

Step 1

Very first step is to create our Command interface that declares execution method .

Command Interface -:

public interface Command
{
public void execute();
}

Step 2

Let’s create our executor of commands . Here I will make only Lights class you can add more to it .

Lights Class

public class Lights {
public Lights()
{

}
public void TurnOn()
{
System.out.println("turning on the lights");
}
public void TurnOff()
{
System.out.println("turning off the lights");
}
}

So the work of Lights is to get on and off when appropriate command is given .

Step 3

Now we will create our concrete commands that are going to implement Command Interface . I will consider only turning on and off lights command here if you want you can add more to it.

TurnOnLights Class

public class TurnOnLights implements Command{
private Lights lights;
public TurnOnLights(Lights lights)
{
this.lights=lights;
}
@Override
public void execute(){
this.lights.TurnOn();
}
}

TurnOffLights Class

public class TurnOffLights implements Command{
private Lights lights;
public TurnOffLights(Lights lights)
{
this.lights=lights;
}
@Override
public void execute(){
this.lights.TurnOff();
}
}

Step 4

Now it is time to create our controller that is going to take the command from invoker and will control the flow and execution of commands .

RemoteController Class

public class RemoteController {
Command command;
public RemoteController()
{

}
public void setCommand(Command command)
{
this.command = command;
}
public void pressButton()
{
this.command.execute();
}
}

Step 5

At last we are going to create our Invoker that is our client which is going to generate a command object .

Main Class

public class Main {
public static void main(String[] args) {
Lights lights=new Lights(); //executor
RemoteController remote=new RemoteController(); //controller
Command c1=new TurnOnLights(lights);
Command c2=new TurnOffLights(lights);
remote.setCommand(c1);
remote.pressButton(); //invoking command
remote.setCommand(c2);
remote.pressButton();
}
}

In the Invoker Class we have created our executer object , remote object and our desired command object , then using a setter we gave the command to remote and for its execution we use pressButton() method . It is similar to pressing a button on remote to turn on lights, turn off lights etc. Now when the pressButton() method is called , the command’s execute() method is invoked and hence the appropriate operation being performed by command is executed by receiver that is our Lights. You can see that the commands are being executed in the order they are given by the client .

Output

Advantages of Command Design Pattern

  • Makes our code extensible as we can add new commands without changing existing code.
  • Reduces coupling between the invoker and receiver of a command.

Real Life Examples of Command Design Pattern

  1. GUI applications: GUI frameworks often utilize the Command pattern extensively. For instance, when you click a button on a graphical user interface, a command object is typically created and executed to perform the corresponding action. This allows the GUI framework to decouple the event trigger (button click) from the specific operation that needs to be performed, providing flexibility and extensibility.
  2. Text editors: Text editors often employ the Command pattern to implement undo/redo functionality. Each user action, such as typing a character, deleting a line, or formatting text, can be encapsulated as a command object. The text editor maintains a history of executed commands, enabling the ability to undo and redo operations by executing the respective command objects in reverse order or forward order.
  3. Remote controls: The Command pattern is commonly used in remote control systems, such as TV remotes or home automation systems. Each button on the remote control is associated with a specific command object. When a button is pressed, the corresponding command object is executed, triggering the desired action on the controlled device (e.g., turning on/off lights, changing channels, adjusting volume).
  4. Job scheduling: Command objects can be utilized in job scheduling systems. Each job or task to be executed is encapsulated as a command object, which contains all the necessary information and logic to perform the task. The job scheduler maintains a queue of command objects and executes them based on predefined criteria, such as priority, time, or dependencies.
  5. Transaction management: In database systems, the Command pattern can be employed to manage transactions. Each database operation, such as inserting a record, updating data, or deleting records, can be encapsulated as a command object. The transaction manager maintains a list of executed commands and provides methods to commit or rollback the transaction by executing or undoing the respective command objects.

Complete code at 👉https://github.com/Neha611/Command-Desing-Pattern

Please leave some 👏 and don’t forget to follow me for more such content .

Thank you 😄

--

--