Open In App

Command Design Pattern

Last Updated : 21 Sep, 2025
Comments
Improve
Suggest changes
24 Likes
Like
Report

Command Design Pattern is a behavioral pattern that encapsulates a request as an object, decoupling the sender from the receiver. It allows requests to be queued, logged, parameterized, or undone/redone, providing flexibility and extensibility in executing operations.
Let us understand with the help of remote control. Each button on a remote is a command object

Command-Design-Pattern
Command Design Pattern

Real Life Software Examples

  • GUI Buttons and Menu :. Each button or menu item (Copy, Paste, Save, Undo) is a command object. The framework doesn’t know the exact action — it just executes the command.
  • Job Queues : AWS SQS, RabbitMQ, Each job/task is wrapped in a command object. Queues hold commands and execute them later or distribute them across systems.
  • Database Transactions : Example are Hibernate, JPA, SQL transaction managers. Each query (INSERT, UPDATE, DELETE) is wrapped as a command. Transactions execute them sequentially, and rollback is possible if one fails.

Components of the Command Design Pattern

  1. Command Interface – Declares the common method (e.g., execute()) for all commands.
  2. Concrete Commands – Implement the interface and encapsulate specific actions (e.g., turn on TV).
  3. Invoker – Initiates the command execution without knowing the details (e.g., remote control).
  4. Receiver – Performs the actual operation defined by the command (e.g., TV, stereo).

When to Use Command Pattern

  • Decoupling – To separate sender from receiver for flexibility and extensibility.
  • Undo/Redo – Supports reversible operations by storing commands.
  • Queues/Logging – Enables command history, logging, or queued execution.
  • Dynamic Configuration – Allows runtime assembly and composition of commands.

When Not to Use

  • Simple Tasks – Overkill for basic, one-off operations.
  • Tight Coupling is Fine – Unnecessary if sender and receiver can stay coupled.
  • Performance Critical – Adds overhead not suitable for high-performance needs.
  • No Undo/Redo Needed – If reversible operations aren’t required.

How to implement Command Design Pattern?

Below are the simple steps to implement the Command Design Pattern:

  1. Create the Command Interface: Define an interface or abstract class that declares the execute() method. This method will be called to carry out the action.
  2. Create Concrete Command Classes: Implement the command interface in multiple classes. Each class will represent a different command and will call the appropriate method on the receiver to perform the specific action.
  3. Define the Receiver Class: This class contains the actual logic that needs to be executed. The command objects will call methods on this receiver to perform actions.
  4. Create the Invoker Class: The invoker triggers the command’s execute() method but doesn’t know the details of the operation. It simply knows that it needs to call the command.
  5. Client Uses the Command: The client creates the concrete command objects and associates them with the receiver. It then assigns commands to the invoker, which will call them when needed.

Command Design Pattern example

Problem Statement:

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?

  • Devices can have different functionalities, so designing a remote control that can easily handle different device types with varying functionalities without becoming highly complex.
  • 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.
  • 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.

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.

C++
// Command interface
public interface Command {
    void execute();
}
Java
// Command interface
public interface Command {
    void execute();
}
Python
from abc import ABC, abstractmethod

class Command(ABC):
    @abstractmethod
    def execute(self):
        pass
JavaScript
// Command interface
class Command {
    execute() {
        throw new Error('Method not implemented.');
    }
}

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.

C++
// 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();
    }
}
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();
    }
}
Python
# Concrete command for turning a device on
class TurnOnCommand:
    def __init__(self, device):
        self.device = device

    def execute(self):
        self.device.turn_on()

# Concrete command for turning a device off
class TurnOffCommand:
    def __init__(self, device):
        self.device = device

    def execute(self):
        self.device.turn_off()

# Concrete command for adjusting the volume of a stereo
class AdjustVolumeCommand:
    def __init__(self, stereo):
        self.stereo = stereo

    def execute(self):
        self.stereo.adjust_volume()

# Concrete command for changing the channel of a TV
class ChangeChannelCommand:
    def __init__(self, tv):
        self.tv = tv

    def execute(self):
        self.tv.change_channel()
JavaScript
/* Concrete command for turning a device on */
class TurnOnCommand {
    constructor(device) {
        this.device = device;
    }

    execute() {
        this.device.turnOn();
    }
}

/* Concrete command for turning a device off */
class TurnOffCommand {
    constructor(device) {
        this.device = device;
    }

    execute() {
        this.device.turnOff();
    }
}

/* Concrete command for adjusting the volume of a stereo */
class AdjustVolumeCommand {
    constructor(stereo) {
        this.stereo = stereo;
    }

    execute() {
        this.stereo.adjustVolume();
    }
}

/* Concrete command for changing the channel of a TV */
class ChangeChannelCommand {
    constructor(tv) {
        this.tv = tv;
    }

    execute() {
        this.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.

C++
// 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");
    }
}
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");
    }
}
Python
# Receiver interface
from abc import ABC, abstractmethod

class Device(ABC):
    @abstractmethod
    def turnOn(self):
        pass
    @abstractmethod
    def turnOff(self):
        pass

# Concrete receiver for a TV
class TV(Device):
    def turnOn(self):
        print('TV is now on')
    def turnOff(self):
        print('TV is now off')
    def changeChannel(self):
        print('Channel changed')

# Concrete receiver for a stereo
class Stereo(Device):
    def turnOn(self):
        print('Stereo is now on')
    def turnOff(self):
        print('Stereo is now off')
    def adjustVolume(self):
        print('Volume adjusted')
JavaScript
/* Receiver interface */
const Device = {
    turnOn: function() {},
    turnOff: function() {}
};

/* Concrete receiver for a TV */
const TV = {
    turnOn: function() {
        console.log('TV is now on');
    },
    turnOff: function() {
        console.log('TV is now off');
    },
    changeChannel: function() {
        console.log('Channel changed');
    }
};

/* Concrete receiver for a stereo */
const Stereo = {
    turnOn: function() {
        console.log('Stereo is now on');
    },
    turnOff: function() {
        console.log('Stereo is now off');
    },
    adjustVolume: function() {
        console.log('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.

C++
// Invoker
public class RemoteControl {
    private Command command;

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

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

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

    public void pressButton() {
        command.execute();
    }
}
Python
# Invoker
class RemoteControl:
    def __init__(self):
        self.command = None

    def set_command(self, command):
        self.command = command

    def press_button(self):
        self.command.execute()
JavaScript
// Invoker
class RemoteControl {
    constructor() {
        this.command = null;
    }

    setCommand(command) {
        this.command = command;
    }

    pressButton() {
        this.command.execute();
    }
}

Complete code for the above example

Below is the complete code for the above example:

C++
// 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
    }
}
Java
import java.util.function.Consumer;

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

// Concrete command for turning a device on
class TurnOnCommand implements Command {
    private Consumer<Void> deviceAction;

    public TurnOnCommand(Consumer<Void> deviceAction) {
        this.deviceAction = deviceAction;
    }

    @Override
    public void execute() {
        deviceAction.accept(null);
    }
}

// Concrete command for turning a device off
class TurnOffCommand implements Command {
    private Consumer<Void> deviceAction;

    public TurnOffCommand(Consumer<Void> deviceAction) {
        this.deviceAction = deviceAction;
    }

    @Override
    public void execute() {
        deviceAction.accept(null);
    }
}

// Concrete command for adjusting the volume of a stereo
class AdjustVolumeCommand implements Command {
    private Runnable stereoAction;

    public AdjustVolumeCommand(Runnable stereoAction) {
        this.stereoAction = stereoAction;
    }

    @Override
    public void execute() {
        stereoAction.run();
    }
}

// Concrete command for changing the channel of a TV
class ChangeChannelCommand implements Command {
    private Runnable tvAction;

    public ChangeChannelCommand(Runnable tvAction) {
        this.tvAction = tvAction;
    }

    @Override
    public void execute() {
        tvAction.run();
    }
}

// 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() {
        if (command != null) {
            command.execute();
        }
    }
}

// Example usage
public class Main {
    public static void main(String[] args) {
        // Create devices
        TV tv = new TV();
        Stereo stereo = new Stereo();

        // Create command objects
        Command turnOnTvCommand = new TurnOnCommand(tv::turnOn);
        Command turnOffTvCommand = new TurnOffCommand(tv::turnOff);
        Command adjustVolumeStereoCommand = new AdjustVolumeCommand(stereo::adjustVolume);
        Command changeChannelTvCommand = new ChangeChannelCommand(tv::changeChannel);

        // 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
    }
}
Python
# Command interface
from abc import ABC, abstractmethod

class Command(ABC):
    @abstractmethod
    def execute(self):
        pass

# Concrete command for turning a device on
class TurnOnCommand(Command):
    def __init__(self, device):
        self.device = device

    def execute(self):
        self.device.turn_on()

# Concrete command for turning a device off
class TurnOffCommand(Command):
    def __init__(self, device):
        self.device = device

    def execute(self):
        self.device.turn_off()

# Concrete command for adjusting the volume of a stereo
class AdjustVolumeCommand(Command):
    def __init__(self, stereo):
        self.stereo = stereo

    def execute(self):
        self.stereo.adjust_volume()

# Concrete command for changing the channel of a TV
class ChangeChannelCommand(Command):
    def __init__(self, tv):
        self.tv = tv

    def execute(self):
        self.tv.change_channel()

# Receiver interface
class Device(ABC):
    @abstractmethod
    def turn_on(self):
        pass

    @abstractmethod
    def turn_off(self):
        pass

# Concrete receiver for a TV
class TV(Device):
    def turn_on(self):
        print('TV is now on')

    def turn_off(self):
        print('TV is now off')

    def change_channel(self):
        print('Channel changed')

# Concrete receiver for a stereo
class Stereo(Device):
    def turn_on(self):
        print('Stereo is now on')

    def turn_off(self):
        print('Stereo is now off')

    def adjust_volume(self):
        print('Volume adjusted')

# Invoker
class RemoteControl:
    def __init__(self):
        self.command = None

    def set_command(self, command):
        self.command = command

    def press_button(self):
        self.command.execute()

# Example usage
if __name__ == '__main__':
    # Create devices
    tv = TV()
    stereo = Stereo()

    # Create command objects
    turn_on_tv_command = TurnOnCommand(tv)
    turn_off_tv_command = TurnOffCommand(tv)
    adjust_volume_stereo_command = AdjustVolumeCommand(stereo)
    change_channel_tv_command = ChangeChannelCommand(tv)

    # Create remote control
    remote = RemoteControl()

    # Set and execute commands
    remote.set_command(turn_on_tv_command)
    remote.press_button()  # Outputs: TV is now on

    remote.set_command(adjust_volume_stereo_command)
    remote.press_button()  # Outputs: Volume adjusted

    remote.set_command(change_channel_tv_command)
    remote.press_button()  # Outputs: Channel changed

    remote.set_command(turn_off_tv_command)
    remote.press_button()  # Outputs: TV is now off
JavaScript
/* Command interface */
class Command {
    execute() {}
}

// Concrete command for turning a device on
class TurnOnCommand extends Command {
    constructor(device) {
        super();
        this.device = device;
    }

    execute() {
        this.device.turnOn();
    }
}

// Concrete command for turning a device off
class TurnOffCommand extends Command {
    constructor(device) {
        super();
        this.device = device;
    }

    execute() {
        this.device.turnOff();
    }
}

// Concrete command for adjusting the volume of a stereo
class AdjustVolumeCommand extends Command {
    constructor(stereo) {
        super();
        this.stereo = stereo;
    }

    execute() {
        this.stereo.adjustVolume();
    }
}

// Concrete command for changing the channel of a TV
class ChangeChannelCommand extends Command {
    constructor(tv) {
        super();
        this.tv = tv;
    }

    execute() {
        this.tv.changeChannel();
    }
}

// Receiver interface
class Device {
    turnOn() {}
    turnOff() {}
}

// Concrete receiver for a TV
class TV extends Device {
    turnOn() {
        console.log('TV is now on');
    }

    turnOff() {
        console.log('TV is now off');
    }

    changeChannel() {
        console.log('Channel changed');
    }
}

// Concrete receiver for a stereo
class Stereo extends Device {
    turnOn() {
        console.log('Stereo is now on');
    }

    turnOff() {
        console.log('Stereo is now off');
    }

    adjustVolume() {
        console.log('Volume adjusted');
    }
}

// Invoker
class RemoteControl {
    constructor() {
        this.command = null;
    }

    setCommand(command) {
        this.command = command;
    }

    pressButton() {
        this.command.execute();
    }
}

// Example usage
(() => {
    // Create devices
    const tv = new TV();
    const stereo = new Stereo();

    // Create command objects
    const turnOnTVCommand = new TurnOnCommand(tv);
    const turnOffTVCommand = new TurnOffCommand(tv);
    const adjustVolumeStereoCommand = new AdjustVolumeCommand(stereo);
    const changeChannelTVCommand = new ChangeChannelCommand(tv);

    // Create remote control
    const 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:

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



Command Design Pattern
Visit Course explore course icon
Article Tags :

Explore