Command

behavioral

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

Intent

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

Motivation

When you need to issue requests to objects without knowing anything about the operation being requested or the receiver of the request, the Command pattern is useful. It decouples the object that invokes the operation from the one that knows how to perform it.

Structure

The pattern involves a Command interface that declares an execution method. ConcreteCommand classes implement Command and invoke operations on a Receiver. An Invoker asks the command to carry out the request.

Participants

  • Command - declares an interface for executing an operation
  • ConcreteCommand - defines a binding between a Receiver object and an action
  • Client - creates a ConcreteCommand object and sets its receiver
  • Invoker - asks the command to carry out the request
  • Receiver - knows how to perform the operations

Pros

  • Decouples the object that invokes the operation from the one that knows how to perform it
  • Commands can be assembled into a composite command
  • Easy to add new commands
  • Supports undo/redo operations

Cons

  • Increases the number of classes
  • Can complicate the codebase

Use Cases

GUI buttons and menu items
Transaction systems
Macro recording
Undo/redo functionality
Job queues

Implementation Tips

Considerations

  • Decide how intelligent commands should be
  • Consider supporting undo operations
  • Think about command queuing
  • Plan for command history

Tips

  • Keep commands simple and focused
  • Store state for undo operations
  • Consider using a command queue
  • Document the receiver's operations

Interactive Code Editor

Related Patterns