Command Pattern

Turn a request into an object so you can queue it, log it, undo it or replay it. A runnable Java 21 text editor with undo, redo and macro commands, Command versus Strategy, lambdas as commands, and Command in executors, job queues and CQRS.

On this page

Simple definition#

The Command pattern wraps a request — “insert this text at position 5” — in an object. Because the request is now a value, it can be stored in a history, undone, redone, queued for later, sent to another thread or logged and replayed.

GoF intent: “Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.” It is also known as Action or Transaction.

The problem#

A text editor needs undo and redo. If menu items and keyboard shortcuts call document.insert(...) directly:

  • there is no record of what was done, so nothing can be undone
  • the same action is wired separately to the menu, the toolbar and the shortcut
  • you cannot record a sequence of actions as a macro.

Real-world analogy#

A restaurant order slip. The waiter (invoker) writes your request on a slip (command) and hands it to the kitchen (receiver). The slip can wait in a queue, be cancelled, or be kept for the bill. The waiter does not need to know how to cook.

Structure#

  • Command — declares execute() (and here undo()).
  • Concrete command (InsertText, DeleteText, MacroCommand) — binds a receiver to an action and its parameters.
  • Receiver (TextDocument) — knows how to perform the work.
  • Invoker (CommandHistory) — asks commands to execute and keeps them for undo.
  • Client — creates commands and gives them to the invoker.
Command — class diagram of the example
classDiagram
    direction LR
    class Command {
        <<interface>>
        +execute()
        +undo()
        +describe() String
    }
    class InsertText {
        -int position
        -String text
    }
    class DeleteText {
        -int position
        -int length
        -String removed
    }
    class MacroCommand {
        <<record>>
        name
        steps
    }
    class CommandHistory {
        -Deque~Command~ undo
        -Deque~Command~ redo
        +run(Command)
        +undo()
        +redo()
    }
    class TextDocument {
        +insert(int, String)
        +delete(int, int) String
    }
    Command <|.. InsertText
    Command <|.. DeleteText
    Command <|.. MacroCommand
    MacroCommand o--> Command : steps
    CommandHistory o--> Command
    InsertText --> TextDocument
    DeleteText --> TextDocument

Java implementation#

The code is in examples/java/src/hub/patterns/command/CommandDemo.java.

TextDocument — receiver View source
/** Receiver: knows how to do the actual work. */
final class TextDocument {
    private final StringBuilder text = new StringBuilder();

    void insert(int position, String s) { text.insert(position, s); }
    String delete(int position, int length) {
        String removed = text.substring(position, position + length);
        text.delete(position, position + length);
        return removed;
    }
    int length() { return text.length(); }
    @Override public String toString() { return "\"" + text + "\""; }
}
Commands View source
/** Command: a request turned into an object, so it can be stored, undone and replayed. */
interface Command {
    void execute();
    void undo();
    String describe();
}

final class InsertText implements Command {
    private final TextDocument doc;
    private final int position;
    private final String text;

    InsertText(TextDocument doc, int position, String text) {
        this.doc = doc; this.position = position; this.text = text;
    }

    @Override public void execute() { doc.insert(position, text); }
    @Override public void undo() { doc.delete(position, text.length()); }
    @Override public String describe() { return "insert '" + text + "' at " + position; }
}

final class DeleteText implements Command {
    private final TextDocument doc;
    private final int position;
    private final int length;
    private String removed = "";              // state captured on execute, needed for undo

    DeleteText(TextDocument doc, int position, int length) {
        this.doc = doc; this.position = position; this.length = length;
    }

    @Override public void execute() { removed = doc.delete(position, length); }
    @Override public void undo() { doc.insert(position, removed); }
    @Override public String describe() { return "delete " + length + " chars at " + position; }
}

/** Macro command: a composite of commands, undone in reverse order. */
record MacroCommand(String name, List<Command> steps) implements Command {
    @Override public void execute() { steps.forEach(Command::execute); }
    @Override public void undo() { steps.reversed().forEach(Command::undo); }
    @Override public String describe() { return "macro '" + name + "'"; }
}
CommandHistory — invoker View source
/** Invoker: executes commands and keeps the undo and redo stacks. It never touches the document. */
final class CommandHistory {
    private final Deque<Command> undo = new ArrayDeque<>();
    private final Deque<Command> redo = new ArrayDeque<>();

    void run(Command c) {
        c.execute();
        undo.push(c);
        redo.clear();                         // a new action invalidates the redo history
    }

    void undo() {
        if (!undo.isEmpty()) {
            Command c = undo.pop();
            c.undo();
            redo.push(c);
            System.out.println("  undo: " + c.describe());
        }
    }

    void redo() {
        if (!redo.isEmpty()) {
            Command c = redo.pop();
            c.execute();
            undo.push(c);
            System.out.println("  redo: " + c.describe());
        }
    }
}
Output View source
After edits:  "Hello, world"
After delete: "Hello,"
  undo: delete 6 chars at 6
              "Hello, world"
  undo: insert ',' at 5
              "Hello world"
  redo: insert ',' at 5
              "Hello, world"
After macro:  "Hello, world Regards, Ana"
  undo: macro 'sign off'
              "Hello, world"

Step-by-step walkthrough#

  1. Each command stores everything it needs: the receiver and the parameters. DeleteText also captures the removed text during execute(), because undo() needs it.
  2. The invoker pushes executed commands on an undo stack. Undo pops one, calls undo(), and pushes it on the redo stack.
  3. A new command clears the redo stack. After you type something new, the old “future” no longer applies. Every editor works this way.
  4. MacroCommand is a composite of commands (the Composite pattern). Its undo() reverses the steps in reverse order, so one undo removes the whole sign-off.

Lambdas as commands#

In Java, Runnable, Callable and any functional interface are command interfaces. When you need only execute(), a lambda is a perfectly good command:

ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor();
pool.submit(() -> emailService.send(welcomeEmail));   // a command, queued and executed later

Use classes when commands need undo, a name for logging, serialization or several methods.

Command versus Strategy#

Both put behaviour in an object, but they answer different questions:

CommandStrategy
QuestionWhat should be done (a request with its arguments)How should something be done (an algorithm)
ArgumentsCaptured in the object at creationPassed in on each call
Typical lifecycleCreated, executed once, maybe undone, storedLong-lived, called many times
ExampleInsertText(doc, 5, ",")DiscountPolicy.discountFor(cart)

Advantages and disadvantages#

AdvantagesDisadvantages
Undo, redo, macros, queuing, scheduling and logging become possibleOne class per action can lead to many small classes
Invoker is decoupled from the receiverCorrect undo needs careful captured state
Commands can be composed and serializedUndo history uses memory; bound it
New commands do not change existing code (OCP)—

When to use it#

  • Undo/redo or transactional behaviour.
  • Queuing, scheduling or executing requests on another thread or machine (job queues, executors).
  • Logging requests so they can be replayed after a crash (write-ahead logs, event logs).
  • Decoupling UI elements from actions (menus, buttons and shortcuts share one command).

When not to use it#

  • A direct method call is enough and none of the above is needed.
  • The request is not really an operation but a choice of algorithm: use Strategy.

Common mistakes#

  • Not clearing the redo stack after a new command.
  • Unbounded history, causing memory growth in long sessions.
  • Commands that depend on global state instead of their stored receiver and arguments, which breaks replay.

Command at architecture scale#

  • Message queues and job systems: a message such as SendInvoice{orderId} is a serialized command.
  • CQRS: the write side receives commands (PlaceOrder) that express intent and may be rejected, as opposed to events (OrderPlaced) that state facts.
  • Event sourcing and write-ahead logs: logged operations are replayed to rebuild state; see Storage Engines.

Real-world uses#

  • java.lang.Runnable and java.util.concurrent.Callable with Executors.
  • Swing’s Action interface and UndoManager / UndoableEdit.
  • Spring Batch steps, Quartz jobs and TaskScheduler tasks.
  • Database transaction logs and Redis’ append-only file (AOF).

Interview questions and answers#

What is the Command pattern? A behavioral pattern that encapsulates a request as an object, so requests can be parameterized, queued, logged and undone.

How do you implement undo with Command? Each command implements undo() using state it captured on execute(). An invoker keeps a stack of executed commands; undo pops and reverses. Redo uses a second stack that is cleared by new commands.

What is a macro command? A command composed of other commands, executed in order and undone in reverse order.

Is a Runnable a command? Yes: an object representing an action to perform later, often on another thread.

Command versus Strategy? Command captures a specific request with its arguments; Strategy is an interchangeable algorithm called with different arguments.

Summary#

  • Command turns a request into an object: storable, queueable, undoable.
  • The invoker manages history; the receiver does the work.
  • Lambdas are commands when only execute() is needed.
  • The idea scales up to job queues, CQRS and write-ahead logs.

References#

  • Gamma, Helm, Johnson, Vlissides. Design Patterns. Addison-Wesley, 1994. Command, p. 233.
  • Eric Freeman, Elisabeth Robson. Head First Design Patterns (2nd edition). O’Reilly, 2020. Chapter 6 (the remote control).