Command pattern

On this page 7

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.

ParticipantResponsibilityExample in a text editor
Command interfaceDeclares execute and often undoEditorCommand
Concrete commandBinds an action to a receiver and argumentsInsertTextCommand
ReceiverPerforms the actual business logicDocument
InvokerTriggers commands, may store historyToolbar button, shortcut handler
ClientCreates and wires commandsApplication startup code
Participants in the command pattern

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.

CapabilityHow it worksTypical use
Undo and redoEach command stores state needed to reverse itselfEditors, design tools
QueuingCommands wait in a queue for a workerBackground jobs, print spoolers
Logging and replaySerialized commands are re-executed laterCrash recovery, audit trails
MacrosA composite command runs a list of commandsRecorded user actions
TransactionsA group of commands commits or rolls back togetherBatch data changes
Remote executionCommands are sent across a networkDistributed task systems
What the command pattern enables

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.

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.

PatternEncapsulatesKey difference from command
Strategy patternAn interchangeable algorithmChooses how to do something, not what request to perform
Observer patternA subscription to eventsNotifies listeners; does not represent one action
Memento patternA snapshot of object stateOften used by commands to implement undo
Chain of responsibilityA sequence of handlersDecides who handles a request, can pass commands along
Callback or closureA function with captured contextLightweight command without undo or metadata
Related patterns and how they differ

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.

SituationRecommendationReason
User-facing editing toolUse commands with undoHistory and redo are expected
Background processingUse serializable commandsJobs must survive restarts
Single fixed actionCall the method directlyExtra classes add no value
Simple callback in UI codeUse a closureLess ceremony, same decoupling
When to use the command pattern

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.