creational

Command

Encapsulate a request as an object for queuing, logging, and undoable operations.

Most code invokes an action by calling a method directly, which fuses the moment of asking with the act of doing. But some features need that action to become a thing you can hold: a job you queue, an operation you can undo, a step you can log and replay. Command turns a request into a first-class object carrying everything needed to perform it later, by someone other than the original caller.

A restaurant order slip — the waiter hands the slip to the kitchen. Slips can be queued or cancelled.

Key Concepts

1
Each action is wrapped in a command object exposing execute(), and often undo(). The command bundles a reference to the receiver that does the real work together with the parameters of the request. An invoker — a button, a scheduler, a queue — triggers commands without knowing what they do, which decouples the sender of a request from its handler. Undo and redo fall out naturally: keep a history stack of executed commands and reverse them by popping and calling undo(); macros are simply commands composed of other commands.
execute()undo()
2
It is the backbone of editor undo/redo, task queues and thread-pool work items, transaction and rollback machinery, GUI actions shared between menus and toolbars, and macro recording. The deliberate trade-off is indirection — a one-line method call becomes a class — so it pays off only when you actually need queuing, logging, undo, or decoupling. Implementing reliable undo() is the genuinely hard part: a command must capture enough prior state to reverse itself precisely, which for destructive operations can mean storing snapshots (often pairing Command with Memento).
undo()