TechnologyZer
technologyzer.com

Understanding Command Design Pattern: A Comprehensive Guide

Introduction

Command design pattern is a behavioral pattern that allows you to encapsulate a request as an object, thereby decoupling the sender of the request from the receiver. In simple terms, it turns a request into a standalone object that contains all the information needed to perform an action at a later time.

Analogy to Explain Command Design Pattern

Imagine you’re in a restaurant, and you want to place an order for a meal. Instead of directly telling the chef what you want, you write down your order on a piece of paper (the command object). The waiter (the invoker) takes this paper and hands it to the chef (the receiver) to prepare your meal.

In this analogy:

  • The command object represents your order, containing all the details of the meal you want.
  • The invoker is like the waiter, who knows how to execute commands but doesn’t need to know the specifics of each command.
  • The receiver is the chef, who knows how to carry out the requested action (preparing the meal) when given a command.

By using the Command pattern, you can achieve several benefits:

  1. Decoupling: The sender and receiver of a request are no longer tightly coupled, allowing for greater flexibility and extensibility.
  2. Undo/Redo: Commands can support undo and redo operations, enabling reversible actions.
  3. Logging and Queuing: Commands can be logged for auditing purposes or queued for execution at a later time.

Overall, the Command pattern promotes a more modular and flexible design by encapsulating requests as objects, making it easier to manage and manipulate them within a system.

6 real world example of Command Design Pattern

  1. In a restaurant ordering system, the Command pattern can represent orders as objects, allowing waitstaff to execute, undo, or redo orders.
  2. A remote control for a TV uses the Command pattern, with each button representing a different command like power on/off or volume up/down.
  3. In a smart home system, the Command pattern can be used to control various devices such as lights, thermostats, and door locks via voice commands.
  4. A text editor implements the Command pattern by encapsulating editing operations like copy, cut, and paste into command objects.
  5. An e-commerce platform uses the Command pattern to handle transactions, with each order representing a command object that can be processed or canceled.
  6. A task scheduler application utilizes the Command pattern to represent scheduled tasks as objects that can be executed at specific times.

Sample Code for Command design pattern:

// Receiver class
class Light {
    boolean isOn;
    public void turnOn() {
        isOn = true;
        System.out.println("Light is ON");
    }

    public void turnOff() {
        isOn = false;
        System.out.println("Light is OFF");
    }
}

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

// Concrete command classes
class LightOnCommand implements Command {
    private Light light;

    public LightOnCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.turnOn();
    }
}

class LightOffCommand implements Command {
    private Light light;

    public LightOffCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.turnOff();
    }
}

// Invoker class
class RemoteControl {
    private List<Command> commands = new ArrayList<>();

    public void addCommand(Command command) {
        commands.add(command);
    }

    public void executeCommands() {
        for (Command command : commands) {
            command.execute();
        }
    }
}

// Client code
public class CommandPatternExample {
    public static void main(String[] args) {
        // Create receiver
        Light light = new Light();

        // Create command objects
        Command lightOnCommand = new LightOnCommand(light);
        Command lightOffCommand = new LightOffCommand(light);

        // Create invoker
        RemoteControl remoteControl = new RemoteControl();

        // Add commands to the invoker
        remoteControl.addCommand(lightOnCommand);
        remoteControl.addCommand(lightOffCommand);

        // Execute commands
        remoteControl.executeCommands();
    }
}

Leave a Comment