Command Design Pattern in Java

Akshat Sharma
6 min readJun 3, 2023

--

Hey everyone 👋

Have you ever wandered how our commands given to any system are executed within no time 😕what kind of design pattern is being used here . So don’t worry because today in this blog we are going to study about one such design pattern . In this blog we are going to know about Command Design Pattern . Points which we are going to cover here are -:

  1. Basic Definition
  2. Components
  3. Basic Implementation
  4. Advantages
  5. Real life examples

So let’s get started . 💁

What is Command Design Pattern ?

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.

For example suppose you have a remote controller through which you can turn on / off the tv , change volume and change channel . So you are invoker of command , the remote controller is controller of command and tv is executer of command . So from invocation of command to its execution the process in between these two is completely hidden from you . So here command design pattern comes into picture it decouples the sender of request from the reciever and control the execution of commands .

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. ConcreteCommand: 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

We will use above example to see the implementation of Command Design Pattern . So in the above example we have a remote controller , invoker , executer and command , so let’s make each one of them .

Step 1

Let’s create our command interface that will contain all the basic operation for particular command .

Command Interface

public interface Command
{
public void execute();
}

So this interface will have just one basic command that is execute .

Step 2

Now we will create our concrete commands that are going to implement Command Interface .

Tv On Command Class

public class TvOnCommand implements Command
{
private TV tv;
public TvOnCommand(TV tv)
{
this.tv = tv;
}
public void execute()
{
this.tv.TurnOn();
}
}

Tv Off Command Class

public class TvOffCommand implements Command
{
private TV tv;
public TvOffCommand(TV tv)
{
this.tv = tv;
}

public void execute()
{
this.tv.TurnOff();
}
}

Step 3

Let’s create our reciever or executer that is our tv that is going to execute above commands .

TV Class


//executor that knows how to execute the command
public class TV
{
public TV()
{

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

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 .

Remote Class


//controller that will be taking the command form the invoker to the executor
public class Remote
{
Command command;
public Remote()
{

}
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 .

Invoker Class

public class Main {
public static void main(String[] args)
{
//client is the invoker

//invoker knows which command to invoke
//executor knows how to execute the command
//controller will take the command from the invoker to the executor

TV tv = new TV(); //executor
Remote remote = new Remote(); //controller

Command tvOnCommand = new TvOnCommand(tv); //tv on cmd
Command tvOffCommand = new TvOffCommand(tv); // tv off cmd

remote.setCommand(tvOnCommand);
remote.pressButton(); //invoking the tv on command

remote.setCommand(tvOffCommand);
remote.pressButton(); //invoking the tv off command

}
}

Output

Let’s see the flow of code .

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 change channel , increase volume 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 reciever that is our TV . You can see that the commands are being executed in the order they are given by the client .

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.

So this was my knowledge on Command Design Pattern , hope you guys got answers to your every question on Command Design Pattern . Please leave some claps and don’t forget to follow me for more such content .

Complete code at 👉https://github.com/akshatsh0610/Command-Design-Pattern

Thank you 😄

--

--