For AI agents: the complete documentation index is available at https://nhanbe.id.vn/llms.txt, the full documentation bundle is available at https://nhanbe.id.vn/llms-full.txt, and this page is available as Markdown at https://nhanbe.id.vn/design-patterns/behavioral/command.md.

Encapsulate a request as an object, allowing parameterization and queuing. You need undo/redo. You want to queue or log operations. Pros: Suppor

Command

Overview

Encapsulate a request as an object, allowing parameterization and queuing.

When to use

  • You need undo/redo.
  • You want to queue or log operations.

Java example

interface Command { void execute(); }

class SaveCommand implements Command {
    private final Document doc;
    SaveCommand(Document doc) { this.doc = doc; }
    public void execute() { doc.save(); }
}

class Invoker {
    void run(Command cmd) { cmd.execute(); }
}

TypeScript example

interface Command { execute(): void; }

class SaveCommand implements Command {
  constructor(private doc: Document) {}
  execute(): void { this.doc.save(); }
}

class Invoker {
  run(cmd: Command): void { cmd.execute(); }
}

Pros and cons

Pros:

  • Supports undo/redo and logging.
  • Decouples invoker from receiver.

Cons:

  • Many small classes.
  • Indirection can be heavy for simple actions.

Common pitfalls

  • Not capturing all necessary state for undo.
  • Creating commands for trivial operations.