Command
Encapsulates a request as an object, allowing you to parameterize clients, queue or log requests, and support undoable operations.
errorWhat Problem Does the Command Pattern Solve?
When you need to issue requests to objects without knowing anything about the operation being requested or the receiver, direct method calls couple the invoker to the receiver. This makes it impossible to queue requests, log them for auditing, or reverse them for undo functionality.
check_circleHow the Command Pattern Works
Wrap each request in a Command object that bundles the receiver, the action, and any parameters. An Invoker holds and executes commands through a uniform execute interface without knowing what each command does. Commands can be stored in a history stack, serialized to a queue, or replayed.
Command Pattern Architecture
Rendering diagram...
Implementation by Language
Command Pattern in the Real World
“Think of a restaurant order ticket. A waiter (invoker) takes your order and writes it on a slip (command). The slip is handed to the kitchen (receiver) which executes it. The waiter doesn't cook anything—they just carry and deliver orders. Tickets can be queued, cancelled before cooking, or reviewed in an audit log at day's end.”
Frequently Asked Questions
helpHow does the Command pattern enable undo/redo?
Each Command object encapsulates an action and stores enough state to reverse it. An undo stack keeps executed commands in order. To undo, pop the last command and call its undo() method. To redo, maintain a second stack of undone commands. This is how text editors and drawing tools implement undo.
helpWhat is the difference between Command and Strategy?
Strategy encapsulates interchangeable algorithms — you swap one for another. Command encapsulates a request as an object — you store, queue, log, or undo it. Strategy is about 'how'; Command is about 'what' (the action itself, deferred for later execution).