Command
09 Mar 2022Intent
Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
Also known as
Action/Transaction
Applicability
Use command pattern when you want to:
- Parameterize objects by an action to perform.
- Specify, queue and execute requests at different times.
- support undo.
- support logging changes so that they can be reapplied in case of a system crash.
- structure a system around high-level operations built on primitives operations.
Structure
Participants
- Command: declares an interface for executing an operation.
- ConcreteCommand: defines a binding between a Receiver object and an action, implements Execute by invoking the corresponding operations on Receiver.
- Client: creates a ConcreteCommand object and sets it's receiver.
- Invoker: asks the command to carry out the request.
- Receiver: knows how to perform the operations associated with carrying out a request. Any class may server as a Receiver.
Collaborations
- The client creates a ConcreteCommand object and specifies it's receiver.
- An Invoker object stores the ConcreteCommand object.
- The onvoker issues a request by calling Execute on the command. When commands are undoable, ConcreteCommand stores state for undoing the command prior to invoking Execute.
- The ConcreteCommand object invokes operations on it's receiver to carry out the request.
Consequences
- Command decouples the object that invokes the operation from the one that knows how to perform it.
- Commands are first-class objects. They can be manipulated and extended like any other object.
- You can assemble commands into a composite command.
- It's easy to add new Commands, because you don't have to change existing classes.
Sample Code
Related Patterns
- A composite can be used to implement MacroCommands
- A memento can keep state the command requires to undo it's effect.
- A command that must be copied before being places on the history list acts as a prototype.