The Wayback Machine - https://web.archive.org/web/20240926115409/https://www.geeksforgeeks.org/command-pattern/
Open In App

Command Design Pattern

Last Updated : 06 Feb, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The Command Design Pattern is a behavioral design pattern that turns a request into a stand-alone object, allowing parameterization of clients with different requests, queuing of requests, and support for undoable operations(action or a series of actions that can be reversed or undone in a system).

command-design-pattern-new-

What is the Command Design Pattern?

The Command Design Pattern is a behavioral design pattern that turns a request into a stand-alone object, allowing parameterization of clients with different requests, queuing of requests, and support for undoable operations.

  • The Command Pattern encapsulates a request as an object, allowing for the separation of sender and receiver.
  • Commands can be parameterized, meaning you can create different commands with different parameters without changing the invoker(responsible for initiating command execution).
  • It decouples the sender (client or invoker) from the receiver (object performing the operation), providing flexibility and extensibility.
  • The pattern supports undoable(action or a series of actions that can be reversed or undone in a system) operations by storing the state or reverse commands.

Components of the Command Design Pattern

1. Command Interface

The Command Interface is like a rulebook that all command classes follow. It declares a common method, execute(), ensuring that every concrete command knows how to perform its specific action. It sets the standard for all commands, making it easier for the remote control to manage and execute diverse operations without needing to know the details of each command.

2. Concrete Command Classes

Concrete Command Classes are the specific commands, like turning on a TV or adjusting the stereo volume. Each class encapsulates the details of a particular action. These classes act as executable instructions that the remote control can trigger without worrying about the nitty-gritty details of how each command accomplishes its task.

3. Invoker (Remote Control)

The Invoker, often a remote control, is the one responsible for initiating command execution. It holds a reference to a command but doesn’t delve into the specifics of how each command works. It’s like a button that, when pressed, makes things happen. The remote control’s role is to coordinate and execute commands without getting involved in the complexities of individual actions.

4. Receiver (Devices)

The Receiver is the device that knows how to perform the actual operation associated with a command. It could be a TV, stereo, or any other device. Receivers understand the specific tasks mentioned in commands. If a command says, “turn on,” the Receiver (device) knows precisely how to execute that action. The Receiver-Command relationship separates responsibilities, making it easy to add new devices or commands without messing with existing functionality.

Command Design Pattern example

Imagine you are tasked with designing a remote control system for various electronic devices in a smart home. The devices include a TV, a stereo, and potentially other appliances. The goal is to create a flexible remote control that can handle different types of commands for each device, such as turning devices on/off, adjusting settings, or changing channels.

What can be the challenges while implementing this system?

  • First challenges is that devices can have different functionalities, so designing a remote control that can seamlessly handle different device types with varying functionalities without becoming overly complex or device-specific.
  • Implementing a remote control that supports various commands without tightly coupling ensuring the remote control can execute commands for different devices without needing extensive modifications for each new command or device type.
  • Designing a system that allows users to customize the behavior of the remote control dynamically

How Command Pattern help to solve above challenges?

The Command Pattern can be employed to address these challenges. It introduces a level of abstraction between the sender of a command (remote control) and the receiver of the command (electronic devices).

  • The Command Pattern decouples the sender (Invoker) from the receiver (Devices). The remote control doesn’t need to know the specific details of how each device operates; it only triggers commands.
  • New devices or commands can be added without modifying existing code. The remote control can work with any device that implements the common command interface.
  • The remote control can dynamically change its behavior by associating different commands.

CommandPatternExampledrawio-(3)

Below is the code of above problem statement using Command Pattern:

1. Command Interface

The Command interface declares a method, often named execute(). This method is meant to encapsulate a specific operation. The interface sets a contract for concrete command classes, defining the execute() method that encapsulates the operation to be performed.

Java




// Command interface
public interface Command {
    void execute();
}


2. Concrete Command Classes

Concrete command classes implement the Command interface. Each class encapsulates a specific operation related to devices. Each concrete command class provides a specific implementation of the execute() method, defining how a particular device operation (turning on, turning off, adjusting volume, changing channel) is executed.

Java




// Concrete command for turning a device on
public class TurnOnCommand implements Command {
    private Device device;
 
    public TurnOnCommand(Device device) {
        this.device = device;
    }
 
    @Override
    public void execute() {
        device.turnOn();
    }
}
 
// Concrete command for turning a device off
public class TurnOffCommand implements Command {
    private Device device;
 
    public TurnOffCommand(Device device) {
        this.device = device;
    }
 
    @Override
    public void execute() {
        device.turnOff();
    }
}
 
// Concrete command for adjusting the volume of a stereo
public class AdjustVolumeCommand implements Command {
    private Stereo stereo;
 
    public AdjustVolumeCommand(Stereo stereo) {
        this.stereo = stereo;
    }
 
    @Override
    public void execute() {
        stereo.adjustVolume();
    }
}
 
// Concrete command for changing the channel of a TV
public class ChangeChannelCommand implements Command {
    private TV tv;
 
    public ChangeChannelCommand(TV tv) {
        this.tv = tv;
    }
 
    @Override
    public void execute() {
        tv.changeChannel();
    }
}


3. Receiver Classes (Devices)

The Device interface declares methods related to device functionality, such as turnOn() and turnOff(). This interface sets a contract for device classes, defining common operations that concrete devices should support.

Java




// Receiver interface
public interface Device {
    void turnOn();
    void turnOff();
}
 
// Concrete receiver for a TV
public class TV implements Device {
    @Override
    public void turnOn() {
        System.out.println("TV is now on");
    }
 
    @Override
    public void turnOff() {
        System.out.println("TV is now off");
    }
 
    public void changeChannel() {
        System.out.println("Channel changed");
    }
}
 
// Concrete receiver for a stereo
public class Stereo implements Device {
    @Override
    public void turnOn() {
        System.out.println("Stereo is now on");
    }
 
    @Override
    public void turnOff() {
        System.out.println("Stereo is now off");
    }
 
    public void adjustVolume() {
        System.out.println("Volume adjusted");
    }
}


4. Invoker Class (Remote Control):

The invoker class holds a reference to a Command object and triggers its execution through the execute() method. The invoker doesn’t know the specific details of the command or the devices. It simply calls the execute() method on the current command, allowing for flexible and dynamic control over different devices.

Java




// Invoker
public class RemoteControl {
    private Command command;
 
    public void setCommand(Command command) {
        this.command = command;
    }
 
    public void pressButton() {
        command.execute();
    }
}


Complete code for the above example

Below is the complete code for the above example:

Java




// Command interface
interface Command {
    void execute();
}
 
// Concrete command for turning a device on
class TurnOnCommand implements Command {
    private Device device;
 
    public TurnOnCommand(Device device) {
        this.device = device;
    }
 
    @Override
    public void execute() {
        device.turnOn();
    }
}
 
// Concrete command for turning a device off
class TurnOffCommand implements Command {
    private Device device;
 
    public TurnOffCommand(Device device) {
        this.device = device;
    }
 
    @Override
    public void execute() {
        device.turnOff();
    }
}
 
// Concrete command for adjusting the volume of a stereo
class AdjustVolumeCommand implements Command {
    private Stereo stereo;
 
    public AdjustVolumeCommand(Stereo stereo) {
        this.stereo = stereo;
    }
 
    @Override
    public void execute() {
        stereo.adjustVolume();
    }
}
 
// Concrete command for changing the channel of a TV
class ChangeChannelCommand implements Command {
    private TV tv;
 
    public ChangeChannelCommand(TV tv) {
        this.tv = tv;
    }
 
    @Override
    public void execute() {
        tv.changeChannel();
    }
}
 
// Receiver interface
interface Device {
    void turnOn();
    void turnOff();
}
 
// Concrete receiver for a TV
class TV implements Device {
    @Override
    public void turnOn() {
        System.out.println("TV is now on");
    }
 
    @Override
    public void turnOff() {
        System.out.println("TV is now off");
    }
 
    public void changeChannel() {
        System.out.println("Channel changed");
    }
}
 
// Concrete receiver for a stereo
class Stereo implements Device {
    @Override
    public void turnOn() {
        System.out.println("Stereo is now on");
    }
 
    @Override
    public void turnOff() {
        System.out.println("Stereo is now off");
    }
 
    public void adjustVolume() {
        System.out.println("Volume adjusted");
    }
}
 
// Invoker
class RemoteControl {
    private Command command;
 
    public void setCommand(Command command) {
        this.command = command;
    }
 
    public void pressButton() {
        command.execute();
    }
}
 
// Example usage
public class CommandPatternExample {
    public static void main(String[] args) {
        // Create devices
        TV tv = new TV();
        Stereo stereo = new Stereo();
 
        // Create command objects
        Command turnOnTVCommand = new TurnOnCommand(tv);
        Command turnOffTVCommand = new TurnOffCommand(tv);
        Command adjustVolumeStereoCommand = new AdjustVolumeCommand(stereo);
        Command changeChannelTVCommand = new ChangeChannelCommand(tv);
 
        // Create remote control
        RemoteControl remote = new RemoteControl();
 
        // Set and execute commands
        remote.setCommand(turnOnTVCommand);
        remote.pressButton(); // Outputs: TV is now on
 
        remote.setCommand(adjustVolumeStereoCommand);
        remote.pressButton(); // Outputs: Volume adjusted
 
        remote.setCommand(changeChannelTVCommand);
        remote.pressButton(); // Outputs: Channel changed
 
        remote.setCommand(turnOffTVCommand);
        remote.pressButton(); // Outputs: TV is now off
    }
}


Output




TV is now on
Volume adjusted
Channel changed
TV is now off


When to use the Command Design Pattern 

  • Decoupling is Needed:
    • Use the Command Pattern when you want to decouple the sender (requester) of a request from the object that performs the request.
    • This helps in making your code more flexible and extensible.
  • Undo/Redo Functionality is Required:
    • If you need to support undo and redo operations in your application, the Command Pattern is a good fit.
    • Each command can encapsulate an operation and its inverse, making it easy to undo or redo actions.
  • Support for Queues and Logging:
    • If you want to maintain a history of commands, log them, or even put them in a queue for execution, the Command Pattern provides a structured way to achieve this.
  • Dynamic Configuration:
    • When you need the ability to dynamically configure and assemble commands at runtime, the Command Pattern allows for flexible composition of commands.

When not to use the Command Design Pattern 

  • Simple Operations:
    • For very simple operations or one-off tasks, introducing the Command Pattern might be overkill.
    • It’s beneficial when you expect your operations to become more complex or when you need to support undo/redo.
  • Tight Coupling is Acceptable:
    • If the sender and receiver of a request are tightly coupled and changes in one do not affect the other, using the Command Pattern might introduce unnecessary complexity.
  • Overhead is a Concern:
    • In scenarios where performance and low overhead are critical factors, introducing the Command Pattern might add some level of indirection and, in turn, impact performance.
  • Limited Use of Undo/Redo:
    • If your application does not require undo/redo functionality and you do not anticipate needing to support such features in the future, the Command Pattern might be unnecessary complexity.



Previous Article
Next Article

Similar Reads

Behavioral Design Pattern | JavaScript Design Pattern
Behavioral design patterns are a subset of design patterns in software engineering that deal with the interaction and responsibilities of objects. These patterns focus on how objects communicate and work together to achieve common tasks. Important Topics for the Behavioral Design Pattern in JavaScript Design Patterns Uses Cases of the Behavioral De
8 min read
Difference between Prototype Design Pattern and Flyweight Design Pattern
The major point in Prototype vs. Flyweight Design Pattern is that Prototype Design Pattern is a creational design pattern whereas Flyweight Design Pattern is a structural design pattern. In this post, we will look into this and more differences between the Prototype and Flyweight Design Patterns. Let us begin with a basic understanding of each of t
2 min read
Facade Design Pattern | JavaScript Design Pattern
Facade design pattern is a Structural design pattern that allows users to create a simple interface that hides the complex implementation details of the system making it easier to use. This pattern intends to create a simplified and unified interface for a set of interfaces hiding the implementation details making it less complex to use. Important
4 min read
Flyweight Design Pattern - JavaScript Design Pattern
The Flyweight Design Pattern is a structural design pattern used in JavaScript to minimize memory usage by sharing the data as much as possible with the related objects. Important Topics for Flyweight Design PatternDiagramatic Representation:Advantages of Flyweight design pattern:Disadvantages of Flyweight design pattern:The shared data typically c
4 min read
Mediator Design Pattern in JavaScript | Design Pattern
The Mediator pattern is a behavioral design pattern that promotes loose coupling between objects by centralizing communication between them. It's particularly useful when you have a complex system with multiple objects that need to interact and you want to avoid the tight coupling that can arise from direct object-to-object communication. Important
5 min read
Difference Between Builder Design Pattern and Factory Design Pattern
Design patterns provide proven solutions to common problems in software design. The Builder and Factory patterns are two popular creational design patterns. The Builder pattern constructs complex objects step by step. In contrast, the Factory pattern creates objects without specifying their exact class. Both patterns streamline object creation but
7 min read
Difference between Strategy pattern and Command pattern
In software design, patterns provide reusable solutions to common problems. The Strategy and Command patterns are two important behavioral design patterns. The Strategy pattern allows the selection of an algorithm at runtime. The Command pattern encapsulates a request as an object. Understanding the differences between these patterns is crucial for
6 min read
CQRS - Command Query Responsibility Segregation Design Pattern
The Command Query Responsibility Segregation (CQRS) design pattern has emerged as a powerful architectural pattern for building complex and scalable software systems. By separating the responsibilities of reading and writing data, CQRS allows for more flexible and efficient designs, particularly in domains with high-performance and scalability requ
9 min read
Command Method Design Pattern in Java
The Command Design Pattern in Java is a behavioral design pattern that turns a request into a stand-alone object, allowing parameterization of clients with different requests, queuing of requests, and support for undoable operations(action or a series of actions that can be reversed or undone in a system). Important Topics for Command Method Design
10 min read
Command Pattern | C++ Design Patterns
The Command Pattern is a behavioral design pattern that focuses on encapsulating a request as an object, thereby decoupling the sender of the request from the receiver. This pattern allows you to parameterize objects with commands, delay or queue a request's execution, and support undoable operations. It's a fundamental pattern for implementing a w
7 min read
Why is Singleton Design Pattern is Considered an Anti-pattern?
Let us explore why the Singleton pattern, a popular way to ensure only one instance of a class exists, is now seen as problematic in software development. In this article, we will discuss drawbacks such as tight coupling between components, difficulty in unit testing, and issues with scalability in larger applications. Important Topics for Singleto
8 min read
Composite Design Pattern | JavaScript Design Patterns
The Composite Design pattern is a way of organizing objects. It helps us handle different objects in a similar way when they are put together to create a structure with parts and wholes. These parts and wholes are like building blocks that can be split into smaller pieces and then put together to make a tree-like structure. The composite design pat
6 min read
Strategy Method Design Pattern | C++ Design Patterns
Strategy Pattern is a behavioral design pattern that defines a family of interchangeable algorithms and allows them to be used interchangeably within a context. This pattern enables the algorithm to be selected at runtime, providing flexibility and promoting code reusability. Important Topics for the Strategy Method in C++ Design Patterns Example o
4 min read
Memento Design Pattern | C++ Design Patterns
Memento Design Pattern is a behavioral design pattern that provides a mechanism for capturing an object's internal state and restoring it to that state at a later time. This pattern is useful when we need to implement features like undo/redo functionality or when we want to save and restore an object's state for various reasons. Important Topics fo
7 min read
Design Patterns Cheat Sheet - When to Use Which Design Pattern?
In system design, selecting the right design pattern is related to choosing the right tool for the job. It's essential for crafting scalable, maintainable, and efficient systems. Yet, among a lot of options, the decision can be difficult. This Design Patterns Cheat Sheet serves as a guide, helping you on the path toward optimal design pattern selec
7 min read
State Method Design Pattern | C++ Design Patterns
In software design, managing the behavior of an object according to its internal state is a common issue. The state pattern addresses this issue by allowing an object to alter its behavior every time its internal state changes. This pattern encapsulates each state in a separate class, which makes it easier to add new states and modify existing stat
7 min read
Template Method Design Pattern | C++ Design Patterns
Template Method Pattern introduces a template in a superclass that defines the steps of an algorithm. These steps may include both common tasks shared among subclasses and specific tasks that need customization. Subclasses then implement or override these steps to modify the algorithm according to their specific needs. Important Topics for Template
7 min read
Difference Between Bridge Pattern and Adapter Pattern
The Bridge Pattern and the Adapter Pattern are structural design patterns in object-oriented software development that primarily target the flexibility and reusability of a design. These two patterns have different roles and are used in different scenarios to solve specific design issues. Important Topics for Bridge Pattern vs Adapter Pattern What
5 min read
Command Method | JavaScript Design Patterns
The command method is a behavioral design pattern that encapsulates an incoming request into a standalone object. This object contains all the necessary information to perform a request including the method to call and parameters. Important Topics for the Command Method in JavaScript Design Patterns Why do the we use Command Method?Command Method e
6 min read
Command Method - Python Design Patterns
Command Method is Behavioral Design Pattern that encapsulates a request as an object, thereby allowing for the parameterization of clients with different requests and the queuing or logging of requests. Parameterizing other objects with different requests in our analogy means that the button used to turn on the lights can later be used to turn on s
3 min read
Strangler Pattern in Micro-services | System Design
The Strangler pattern is an architectural approach employed during the migration from a monolithic application to a microservices-based architecture. It derives its name from the way a vine slowly strangles a tree, gradually replacing its growth. Similarly, the Strangler pattern involves replacing parts of a monolithic application with microservice
4 min read
SAGA Design Pattern
SAGA pattern is a design pattern that is a long-lived sequence of smaller transactions. This pattern is used to manage and maintain data consistency across multiple microservices. Each transaction is executed by a single service, and the state changes are broadcasted to other services involved in the Saga. It helps to maintain data consistency by p
7 min read
10 Best Python Design Pattern Books for Beginners to Advanced
Imagine you're building different types of furniture using the same basic materials (like wood, screws, and nails). Instead of starting from scratch every time, you create templates or instructions for making specific types of furniture. These templates tell you what pieces to use, how to assemble them, and how to add unique features. In software p
4 min read
Abstract Factory Pattern | C++ Design Patterns
Abstract Factory Pattern is a creational design pattern used in object-oriented programming. It provides an interface for creating families of related or dependent objects without specifying their concrete classes. This pattern is a way to encapsulate the creation of objects and ensure that they are compatible and properly configured. In this artic
6 min read
Abstract Factory Pattern | JavaScript Design Patterns
Abstract Factory Pattern is to abstract the process of object creation by defining a family of related factory methods, each responsible for creating a different type of object. These factory methods are organized within an abstract factory interface or class, and the client code uses this interface to create objects. Important Topics for the Abstr
6 min read
Bridge Method | JavaScript Design Pattern
In software design, as systems grow and evolve, the complexity of their components can increase exponentially. This complexity often arises from the intertwining of different functionalities and features, making the system rigid, less maintainable, and harder to scale. The Bridge design pattern emerges as a solution to this problem, offering a way
9 min read
Proxy Pattern | C++ Design Patterns
Design Patterns are an essential part of software engineering, offering proven solutions to common problems encountered during software development. One such pattern is the Proxy Pattern. The Proxy Pattern is a structural design pattern that provides a surrogate or placeholder for another object, allowing you to control access to it. This pattern c
7 min read
Flyweight Pattern | C++ Design Patterns
A flyweight pattern is a structural design pattern used to optimize memory usage and performance when dealing with a large number of objects that share some common characteristics. It achieves this by separating an object's intrinsic state (shared among multiple objects) from its extrinsic state (unique to each object) and storing the intrinsic sta
9 min read
Introduction to Decorator Pattern in C++ | Design Patterns
The Decorator Pattern is a structural design pattern in software engineering that enables the dynamic addition of new behaviors or responsibilities to individual objects without altering their underlying class structure. It achieves this by creating a set of decorator classes that are used to wrap concrete components, which represent the core funct
12 min read
Memento Method - JavaScript Design Pattern
A behavioral design pattern in JavaScript called Memento focuses on externalizing and capturing an object's internal state so that it can later be restored. When you need to add features like undo/redo functionality, history tracking, or reverting an item to a former state, this pattern is quite helpful. Important Topics for the Memento MethodUnder
6 min read
Article Tags :