Command

Category

Behavioral pattern

Problem

Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

Solution

  • Create a Command interface with an execute() method
  • Concrete command objects wrap a receiver and a method call
  • The invoker calls execute() on the command without knowing the receiver

Structure

  • Command: Interface declaring execute()
  • ConcreteCommand: Defines a binding between a Receiver and an action
  • Invoker: Requests the command to execute
  • Receiver: Knows how to perform the operation
  • Client: Creates the ConcreteCommand and sets its receiver

Key Benefits

  • Decouples invoker from receiver — The invoker doesn’t need to know how the action is performed
  • Supports undo/redo — Commands can store state for reversal
  • Queuing and logging — Commands can be queued, logged, or transmitted
  • Macro commands — Multiple commands can be combined into a single operation

Trade-offs

  • Can lead to many command classes for simple operations
  • Adds abstraction overhead for straightforward use cases

When to Use

  • You want to parameterize objects with an action to perform
  • You want to specify, queue, and execute requests at different times
  • You want to support undo operations
  • You want to support logging and transactional systems

Examples