design patterns · behavioral

Command

Encapsulates a request as an object, enabling parameterization, queuing, logging, and undo/redo operations.

mediumbehavioral1h
Ask GPTConfidence

Pattern

Overview

Intent

Encapsulate a request as an object, thereby allowing parameterization of clients with different requests, queuing or logging of requests, and support for undoable operations.

Real-World Analogy

A restaurant order slip - the waiter (Invoker) takes the slip (Command) to the kitchen (Receiver) which executes it. The slip can be queued, logged, or cancelled.

When you need to decouple an action from who triggers it, encapsulate the action in a Command object. The invoker calls execute() without knowing what happens; the command delegates to the receiver.

Command interface has execute() and undo(). ConcreteCommand holds a reference to the receiver and implements the operation. Invoker stores and triggers commands. Client assembles command + receiver and gives them to the invoker.

When to use

Undo/redo systems, transaction management, task queues, macro recording, GUI button actions, remote controls - any case where actions must be objects.

When not to

When no queuing, logging, or undo is needed - a simple method call is cleaner.

Participants

CommandConcreteCommandInvokerReceiverClient

Key Insights

  • Command pattern is the foundation of event sourcing - every state change is a stored command
  • A history stack of commands enables unlimited undo/redo
  • Macro commands (CompositeCommand) combine multiple commands into one
  • Java Runnable and Callable are simplified Command interfaces