Command Pattern

April 5, 2026

Command = encapsulates a request as an object, decouples the sender (Invoker) from the receiver (business logic).

Example: Think of remote control:

  • Button = Invoker
  • Command = instruction (turn on TV)
  • TV = Receiver

👉 The remote doesn’t know how TV works, it just calls execute()

interface Command {
    void execute();
}

// Receiver
class TV {
    void on() { System.out.println("TV ON"); }
    void off() { System.out.println("TV OFF"); }
}

// Concrete Commands
class TurnOnCommand implements Command {
    private TV tv;
    public TurnOnCommand(TV tv) { this.tv = tv; }

    public void execute() {
        tv.on();
    }
}

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

    public void execute() {
        tv.off();
    }
}

// Invoker
class Remote {
    private Command command;

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

    public void press() {
        command.execute();
    }
}

How to use

TV tv = new TV();
Command on = new TurnOnCommand(tv);

Remote remote = new Remote();
remote.setCommand(on);
remote.press(); // TV ON

âś… Pros

  • Decouples sender & receiver
  • Easy to add new commands
  • Supports undo/redo
  • Good for task queues

❌ Cons

  • Many small classes
  • Can over-engineer simple logic