design patterns ·

Command

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

medium1hgeneraljava
Ask GPTConfidence

Theory

Explanation

Intuition first, formal definition second. Skim the bullets if you already know this; read the prose if you don't.

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.

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