Behavioral pattern · Visual logic

Command Pattern: Turn an Action into Data

Command packages a request as an object so actions can be queued, logged, retried, composed, or reversed independently from the caller.

Problem

A caller knows too much about how an operation executes, making undo, scheduling, and retry behavior difficult to add.

Rule

Represent each request behind an execute contract and store everything required to perform or reverse that request.

Run
  1. CALLER creates a command describing the requested operation.
  2. INVOKER queues, records, or executes the command without domain details.
  3. COMMAND delegates to its receiver and may preserve state for undo.
Output

Operations become first-class values that infrastructure can manage without understanding the domain action.

Run it in the real world

An editor stores insert, delete, and format commands in history so the toolbar can execute them and the user can undo them later.

Go deeper

This is an original explanation and example inspired by Head First Design Patterns. The book covers the complete pattern, design principles, and implementation detail.

Retail links are not affiliate links yet. If that changes, this page will clearly disclose it.