The command pattern is a behavioral design pattern that turns a request into a stand-alone object containing everything needed to perform it: the action, the target and the parameters. In software architecture and everyday programming, it decouples the object that issues a request from the object that carries it out, which makes actions easy to queue, log, schedule, undo and replay.
The pattern was described by the Gang of Four in 1994, but its idea appears far beyond classic object-oriented code: job queues, undo stacks, macro recorders, transactional scripts and the command side of CQRS all rely on representing an operation as data.
How the command pattern separates request and execution
The pattern introduces a common command interface, usually with a single execute method. Each concrete command stores a reference to the receiver that does the real work, plus the arguments the operation needs. The invoker, such as a button, menu or scheduler, holds commands and calls execute without knowing what they do.
A client assembles the configuration by creating commands and handing them to invokers. Because the invoker depends only on the interface, new operations can be added without changing invoker code, which is a direct application of the open-closed principle from the SOLID principles.
The table below lists the participants and their responsibilities.
| Participant | Responsibility | Example in a text editor |
|---|---|---|
| Command interface | Declares execute and often undo | EditorCommand |
| Concrete command | Binds an action to a receiver and arguments | InsertTextCommand |
| Receiver | Performs the actual business logic | Document |
| Invoker | Triggers commands, may store history | Toolbar button, shortcut handler |
| Client | Creates and wires commands | Application startup code |
Capabilities gained by treating actions as objects
Once an operation is an object, it can be stored, passed around and inspected like any other value. This single property unlocks several capabilities that would otherwise require tangled conditional code.
| Capability | How it works | Typical use |
|---|---|---|
| Undo and redo | Each command stores state needed to reverse itself | Editors, design tools |
| Queuing | Commands wait in a queue for a worker | Background jobs, print spoolers |
| Logging and replay | Serialized commands are re-executed later | Crash recovery, audit trails |
| Macros | A composite command runs a list of commands | Recorded user actions |
| Transactions | A group of commands commits or rolls back together | Batch data changes |
| Remote execution | Commands are sent across a network | Distributed task systems |
Undo support is the classic motivation. The invoker pushes each executed command onto a history stack; undo pops the top command and calls its undo method, while redo re-executes it from a second stack. Commands must capture enough prior state to reverse their effect, either by storing the old values or by computing an inverse operation.
Command pattern compared with related patterns
The command pattern is often confused with patterns that also wrap behavior in objects. The difference lies in what the object represents: a command is a specific request to be performed, often with its own arguments and history, while other patterns represent algorithms, notifications or saved states.
| Pattern | Encapsulates | Key difference from command |
|---|---|---|
| Strategy pattern | An interchangeable algorithm | Chooses how to do something, not what request to perform |
| Observer pattern | A subscription to events | Notifies listeners; does not represent one action |
| Memento pattern | A snapshot of object state | Often used by commands to implement undo |
| Chain of responsibility | A sequence of handlers | Decides who handles a request, can pass commands along |
| Callback or closure | A function with captured context | Lightweight command without undo or metadata |
In languages with first-class functions, a plain closure often replaces a simple command class. A full command object becomes worthwhile when the operation needs undo, serialization, a name for logging or validation before execution.
Applying the pattern in modern architectures
At the architectural level, commands describe intentions to change state. In CQRS (command query responsibility segregation), a command such as PlaceOrder is a message validated and processed by a single command handler, while queries read data through a separate path. Combined with event sourcing, each handled command produces events that become the durable record.
In domain-driven design and hexagonal architecture, commands form the input boundary of the application layer. Controllers translate HTTP requests into command objects, and handlers call domain logic, which keeps transport details out of the core. Message buses and mediator libraries route commands to handlers and add cross-cutting behaviors such as logging, authorization and retries.
The following decision table indicates when the full pattern pays off.
| Situation | Recommendation | Reason |
|---|---|---|
| User-facing editing tool | Use commands with undo | History and redo are expected |
| Background processing | Use serializable commands | Jobs must survive restarts |
| Single fixed action | Call the method directly | Extra classes add no value |
| Simple callback in UI code | Use a closure | Less ceremony, same decoupling |
Limitations and common mistakes
The main cost of the pattern is class proliferation: every operation becomes its own type, and large applications can accumulate hundreds of small command classes. Teams should watch for the following problems.
- Incomplete undo state: a command that does not capture the previous value cannot reverse itself correctly after other changes.
- Commands holding live references: storing mutable receivers in a long history can leak memory or replay against changed objects.
- Logic inside commands: putting business rules in the command rather than the receiver duplicates domain logic across classes.
- Non-idempotent replay: re-running logged commands after a failure can apply effects twice unless commands are designed to be idempotent.
The short version
The command pattern means writing each action down on a ticket before anyone performs it. A restaurant waiter does not cook; the waiter writes the order on a slip and hands it to the kitchen.
Because the order exists on paper, it can wait in line, be checked, be canceled or be repeated. In software, the ticket is a small object describing one request, and that makes features like undo and job queues straightforward.
Where it makes a difference
A team building a browser-based diagram editor implements every user action, from moving a shape to changing a color, as a command with execute and undo. The editor keeps a history stack of the last 100 commands, so users can press undo repeatedly and recover from mistakes without any feature-specific code.
The same command objects are serialized and sent to the server for real-time collaboration. Other users’ editors receive the commands and apply them in order, and when a connection drops, the client replays the unsent commands after reconnecting. One design decision thus delivers undo, collaboration and recovery together.