Command
Intent
Turns a request into a stand-alone object containing all information about the request.
Problem
Buttons, menu items and shortcuts all trigger “save”, and you need undo.
Solution
Wrap each action in a command object with execute (and undo); invokers just call execute.
Real-world analogy
Think of it like this
A restaurant ticket: the waiter writes your order down and the chef executes it later, in order.
Structure
Hover or tap a numbered role to highlight it in the diagram.
- 1Invoker — Invoker (sender) triggers the command instead of calling the receiver directly.
- 2Command — Command declares a single execution method.
- 3ConcreteCommand — Concrete Commands store parameters and pass the call to a receiver.
- 4Receiver — Receiver contains the actual business logic.
- 5Client — Client creates and configures commands, then hands them to invokers.
Code example
A Go code sample for Command is coming soon. Factory Method, Singleton, Decorator, Observer and Strategy already have code in all six languages.
Applicability
Use Command when parameterising objects with operations.
Use Command when queuing, scheduling or remote execution.
Use Command when undo / redo.
Pros and cons
Pros
- Decouples invokers from receivers
- Undo / redo, deferred execution, composite commands
Cons
- An extra layer between senders and receivers
Relations with other patterns
Check yourself
Check yourself
A drawing app needs undo / redo for every user action and a macro recorder.
Saved in this browser only. Part of Behavioral patterns (0/11).