← Back to Home

Command Pattern

Encapsulate a request as an object, thereby letting you parameterize clients with different requests.

What is it?

The Command pattern turns requests into objects allowing for parameterization, queuing, or logging of requests.

Example

Light is currently: Off

interface Command {
  execute(): void;
}

class Light {
  isOn = false;
  turnOn() {
    this.isOn = true;
  }
  turnOff() {
    this.isOn = false;
  }
}

class TurnOnCommand implements Command {
  constructor(private light: Light) {}
  execute() {
    this.light.turnOn();
  }
}

class TurnOffCommand implements Command {
  constructor(private light: Light) {}
  execute() {
    this.light.turnOff();
  }
}

class RemoteControl {
  private command: Command | null = null;
  setCommand(command: Command) {
    this.command = command;
  }
  pressButton() {
    if (this.command) this.command.execute();
  }
}

// Usage
const light = new Light();
const remote = new RemoteControl();

const onCommand = new TurnOnCommand(light);
remote.setCommand(onCommand);
remote.pressButton();

const offCommand = new TurnOffCommand(light);
remote.setCommand(offCommand);
remote.pressButton();

Common Uses

  • GUI buttons and menu items
  • Undo/Redo operations
  • Task scheduling

When to Use

  • To parameterize objects with operations
  • To queue or log requests
  • To support undoable operations

Caution

  • Can result in a large number of command classes
  • May increase system complexity