Command Pattern - Encapsulating Actions in TypeScript

Master the Command pattern for encapsulating actions as objects. TypeScript examples for undo/redo, task queues, macro recording, and transaction systems.

Behavioral

Detailed Explanation

Command Pattern

The Command pattern encapsulates a request as an object, thereby allowing you to parameterize clients with different requests, queue or log requests, and support undoable operations.

Core Components

  1. Command (interface): Declares execute() and optionally undo()
  2. Concrete Command: Implements the command and stores the receiver reference plus parameters
  3. Receiver: The object that actually performs the work
  4. Invoker: Asks the command to carry out the request (does not know the concrete command)

Undo/Redo Implementation

interface Command {
  execute(): void;
  undo(): void;
  describe(): string;
}

class MoveCommand implements Command {
  private prevX: number;
  private prevY: number;

  constructor(private element: UIElement, private dx: number, private dy: number) {
    this.prevX = element.x;
    this.prevY = element.y;
  }

  execute() {
    this.element.x += this.dx;
    this.element.y += this.dy;
  }

  undo() {
    this.element.x = this.prevX;
    this.element.y = this.prevY;
  }

  describe() { return \`Move (\${this.dx}, \${this.dy})\`; }
}

Command Queue

Commands can be serialized and stored in a queue for deferred execution. This is the basis for task queues, job schedulers, and event sourcing systems where the command history becomes the source of truth.

Macro Commands

A macro command is a composite of multiple commands executed as a unit. It combines the Command and Composite patterns to batch operations together.

Comparison with Strategy

Both encapsulate behavior in objects. The difference is scope: Strategy swaps the algorithm used for a specific task; Command wraps an entire request with its parameters. Commands are typically one-shot actions that can be stored, queued, and undone.

Use Case

Command is essential for text editor undo/redo systems, GUI button actions (each button holds a command object), task queue and job scheduling systems, transaction systems that need rollback, and macro recording in productivity applications.

Try It — Design Pattern Reference

Open full tool