Command Pattern

November 24, 202612 minutes

How does Ctrl+Z know what to undo? Learn how the Command pattern turns a call into an object you can store, queue, combine and reverse, with diagrams, Java code, and a narrated video.

Open any text editor. Type Hello. Make it bold. Then type world. Now press Ctrl+Z: world disappears. Press it again, and the bold is gone. Once more, and you’re back to an empty page. Here’s the puzzle: a method call is gone the moment it returns. So what exactly is the editor undoing? It must have kept each action as something it can hold on to. That something has a name, the Command pattern, and its whole idea is one sentence: turn the call into an object.

Prefer to watch? The narrated video above covers the same lesson (about 9 minutes). The article follows it section by section, with diagrams, a little extra depth, and the complete code.

Ctrl+Z

Three actions, then three undos, in reverse order:

State diagram of the document: empty, then Hello after inserting Hello, then a bold Hello after making it bold, then bold Hello plus world after inserting world; each Ctrl+Z goes back one step, in reverse order, to the empty page. State diagram of the document: empty, then Hello after inserting Hello, then a bold Hello after making it bold, then bold Hello plus world after inserting world; each Ctrl+Z goes back one step, in reverse order, to the empty page.
Undo walks back through the actions in reverse. The editor must have kept them.

To undo, queue or replay an action, the program needs the action as a thing, not as a call that already happened.

The to-do card

Think of a to-do card. Instead of doing a task on the spot, you write it down. On the front: insert “Hello” at the start. And on the back, how to take it back: delete those five letters again.

Now the task is a thing. The card can wait in a tray until someone is free. It can be filed, so you know what happened. Whoever picks it up can do it, without knowing why. And you can clip several cards together into one bigger job.

A written to-do card, with what to do on the front and how to undo it on the back, can wait in a tray, which is a queue; be filed, which is a log; be picked up by anyone, which is the invoker; be clipped together, which is a macro; or be flipped over, which is undo. A written to-do card, with what to do on the front and how to undo it on the back, can wait in a tray, which is a queue; be filed, which is a log; be picked up by anyone, which is the invoker; be clipped together, which is a macro; or be flipped over, which is undo.
Once a request is written down, it can be stored, passed on and reversed.

A request that’s written down can be stored, passed on, and reversed.

The obvious way: every entry point calls the document

Back to the editor. The obvious first version wires every entry point straight to the document. The bold button calls bold on the document. The bold menu item does exactly the same. And so does the keyboard shortcut, Ctrl+B:

class BoldButton {
    void onClick() { editor.document().bold(editor.selection()); }
}

class BoldMenuItem {
    void onSelect() { editor.document().bold(editor.selection()); }
}

class Shortcuts {
    void onKey(KeyEvent key) {
        if (key.is("Ctrl+B")) editor.document().bold(editor.selection());
        if (key.is("Ctrl+Z")) { /* undo... what? */ }
    }
}

Then you get to Ctrl+Z. Undo… what? Nothing was written down. Each call happened, and was forgotten.

The bold button, the bold menu item and the Ctrl+B shortcut each call document.bold directly; Ctrl+Z has nothing to undo because no call was recorded. The bold button, the bold menu item and the Ctrl+B shortcut each call document.bold directly; Ctrl+Z has nothing to undo because no call was recorded.
When the call happens on the spot, nothing remembers it.

And to be fair, it works. For a small app, it’s fine. But notice that the same call already lives in three places.

Why it breaks: undo, repeat, macros, and three copies

Look at what undo actually needs. To undo bold, you must know how that text looked before (italic? already partly bold?). But the click handler has already returned, and that knowledge is gone.

And undo isn’t the only request. Redo. Repeat the last action. Record a macro. Run something later. Every one of them needs the action as data, not as a call that already happened.

Undo, redo, repeat last action, record a macro and run it later all need the same thing: the action kept as data, which direct calls don't provide. Undo, redo, repeat last action, record a macro and run it later all need the same thing: the action kept as data, which direct calls don't provide.
Five features, one missing ingredient.

Meanwhile, every new feature has to be added to the button, the menu, and the shortcut. Three copies. The entry points are welded to the document. (Copy-pasted calls that must change together are a recipe for Shotgun Surgery.)

A call you didn’t keep is a call you can’t undo.

The key insight: turn the call into an object

Here’s the key insight. Wrap each request in an object, behind one tiny interface with two methods. execute does it. undo takes it back. The front and the back of the card:

interface Command {
    void execute();
    void undo();
}

That gives us four roles:

RoleIn the editorKnows
ReceiverDocumenthow to do the real work (insert, bold, setStyle)
CommandMakeBold, InsertTextits receiver and its arguments: everything needed to run the request later
Invokerbutton, menu item, shortcut, Historyonly “some command”; it calls execute
Clientthe code that wires the editorcreates the command and hands it to the invoker

Now the button and the document don’t know each other at all.

Class diagram: the client creates MakeBold and hands it to the Button, the invoker, which holds a Command; Command is an interface with execute and undo; MakeBold and InsertText implement it and call the Document, the receiver. Class diagram: the client creates MakeBold and hands it to the Button, the invoker, which holds a Command; Command is an interface with execute and undo; MakeBold and InsertText implement it and call the Document, the receiver.
The invoker knows only the interface; the command knows the receiver.
Sequence: the client creates a MakeBold command with the document and the range and gives it to the button; later the user clicks; the button calls execute on the command; the command calls bold on the document. The button never talks to the document. Sequence: the client creates a MakeBold command with the document and the range and gives it to the button; later the user clicks; the button calls execute on the command; the command calls bold on the document. The button never talks to the document.
Created now, triggered later, by an invoker that doesn't know the work.

Turn the call into an object.

Building the commands

Let’s build the first command: InsertText. It stores the document, the position, and the text: its receiver, and its arguments. execute inserts the text at that position, and undo deletes exactly that many characters, from the same spot.

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

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

    public void execute() { doc.insert(position, text); }
    public void undo()    { doc.delete(position, text.length()); }
}

MakeBold is trickier. Once the text is bold, you can’t tell how it looked before. So the command remembers. In execute, it first saves the current style in a field, and then applies bold. undo puts the saved style back: italic again, exactly as it was.

class MakeBold implements Command {
    private final Document doc;
    private final Range range;
    private Style before;                        // remembered for undo

    MakeBold(Document doc, Range range) { this.doc = doc; this.range = range; }

    public void execute() { before = doc.styleAt(range); doc.bold(range); }
    public void undo()    { doc.setStyle(range, before); }
}
Sequence: on execute, MakeBold asks the document for the style at the range, gets italic, keeps it in its before field, then calls bold; on undo, it calls setStyle with the saved italic style. Sequence: on execute, MakeBold asks the document for the style at the range, gets italic, keeps it in its before field, then calls bold; on undo, it calls setStyle with the saved italic style.
The command fills in the back of its own card while it works.

Each command is a small class that does one thing, and you can test it on its own: run execute then undo on a document and assert it’s unchanged. (For commands whose undo is hard to compute, an alternative is to store a snapshot of the receiver’s state, the Memento pattern; it’s simpler but uses more memory.)

The invoker and the history

Now, where do the commands go? Into a history with two stacks: done, and undone.

  • run executes a command and pushes it onto the done stack.
  • undo pops the top command, calls its undo, and moves it to the undone stack.
  • redo does the reverse: it pops from undone, executes again, and pushes it back onto done.
  • And if you do something new after an undo, run clears the redo stack, because that old future no longer exists.
class History {
    private final Deque<Command> done = new ArrayDeque<>();
    private final Deque<Command> undone = new ArrayDeque<>();

    void run(Command c) {
        c.execute();
        done.push(c);
        undone.clear();
    }

    void undo() {
        if (done.isEmpty()) return;
        Command c = done.pop();
        c.undo();
        undone.push(c);
    }

    void redo() {
        if (undone.isEmpty()) return;
        Command c = undone.pop();
        c.execute();
        done.push(c);
    }
}
Two stacks: run pushes a command onto the done stack and clears undone; undo moves the top command from done to undone after calling its undo; redo moves it back from undone to done after calling execute again. Two stacks: run pushes a command onto the done stack and clears undone; undo moves the top command from done to undone after calling its undo; redo moves it back from undone to done after calling execute again.
Undo and redo are just commands moving between two stacks.

We run insert text, then make bold. Undo pops MakeBold and the bold comes off; redo puts it back. Look at the wiring: the button, the menu item, and the shortcut all do the same thing, create a MakeBold command and hand it to the history. Ctrl+Z and Ctrl+Y just call undo and redo:

boldButton.onClick(() -> history.run(new MakeBold(doc, editor.selection())));
boldMenuItem.onSelect(() -> history.run(new MakeBold(doc, editor.selection())));
shortcuts.bind("Ctrl+B", () -> history.run(new MakeBold(doc, editor.selection())));
shortcuts.bind("Ctrl+Z", history::undo);
shortcuts.bind("Ctrl+Y", history::redo);

One history, any number of entry points. And none of them knows about the document. A real editor would also create the MakeBold in one place (an Action object or a small factory method), so the three bindings share it.

Macros, queues and logs

Because commands are objects, you can combine them. A macro is a command made of commands. A “title” macro inserts some text, makes it bold, and centers it. execute runs the steps in order, and undo runs them in reverse: the last thing done is the first thing undone.

class Macro implements Command {
    private final List<Command> steps;

    Macro(List<Command> steps) { this.steps = List.copyOf(steps); }

    public void execute() { steps.forEach(Command::execute); }
    public void undo()    { steps.reversed().forEach(Command::undo); }
}

(List.reversed() is Java 21; on older versions, iterate a ListIterator from the end.)

A Macro command holds InsertText, MakeBold and Center. Execute runs them in order: 1 InsertText, 2 MakeBold, 3 Center. Undo runs them in reverse: 1 Center, 2 MakeBold, 3 InsertText. A Macro command holds InsertText, MakeBold and Center. Execute runs them in order: 1 InsertText, 2 MakeBold, 3 Center. Undo runs them in reverse: 1 Center, 2 MakeBold, 3 InsertText.
Last done, first undone.

And the same objects can do more. Put them in a queue, to run later. Write them to a log, and replay them after a crash (that’s how many databases and collaborative editors recover). Or send them to another machine. A macro whose steps all undo correctly undoes correctly as a whole: a macro is the Composite pattern applied to commands.

A realistic example: a job queue

Here’s a realistic example: a background job queue. A customer finishes an order, and the app has to email an invoice. Instead of sending it during the web request, the app writes a job, SendInvoiceEmail, and drops it into a queue. The request returns at once. A worker picks the job up when it’s free. If the mail server is down, the job fails, goes back into the queue, and is retried later.

Sequence: the web request enqueues a SendInvoiceEmail job and returns at once; worker 1 takes the job but the mail server is down, so the job goes back to the queue; later worker 2 takes it and the email is sent. Sequence: the web request enqueues a SendInvoiceEmail job and returns at once; worker 1 takes the job but the mail server is down, so the job goes back to the queue; later worker 2 takes it and the email is sent.
A job is a command that waits for its turn.

In code, the job is a tiny record. It holds just the invoice id, not the invoice itself, because by the time it runs, the data may have changed (and an id is easy to store in a database or a message broker):

interface Job {
    void run(Services services);
}

record SendInvoiceEmail(String invoiceId) implements Job {
    public void run(Services services) {
        services.mailer().send(services.invoices().find(invoiceId));
    }
}

jobQueue.enqueue(new SendInvoiceEmail("INV-2041"));   // stored, run by a worker, retried on failure

Java has the simplest version built in. An ExecutorService takes runnables, and a Runnable is a command: something to run later, somewhere else.

ExecutorService workers = Executors.newFixedThreadPool(4);
workers.submit(() -> mailer.send(invoice));   // a Runnable is a command: run it later, elsewhere

Notice what’s missing: undo. You can’t unsend an email. For actions with outside effects, you compensate instead, for example by sending a correction (the same idea as a refund instead of a “cancelled” payment). And because every job is just data, the queue doubles as a record of everything the app was asked to do. Since a retried job may run twice, make jobs idempotent: running SendInvoiceEmail("INV-2041") a second time should notice the email was already sent.

Command vs Strategy

Command often gets confused with the Strategy pattern. Both put behavior behind an interface, and the class diagrams look alike.

  • A strategy is how to do a task the object is already doing. A sort calls its comparator again and again. Swap the comparator, and you change the algorithm.
  • A command is what to do, and when. It’s one whole request (receiver plus arguments), packed up now, run later, usually once, and maybe undone.
Strategy: orders.sort calls the byTotal comparator many times during one sort; swapping it changes the algorithm. Command: a MakeBold command with its document and range is created now, run later once by the history, and may be undone. Strategy: orders.sort calls the byTotal comparator many times during one sort; swapping it changes the algorithm. Command: a MakeBold command with its document and range is created now, run later once by the history, and may be undone.
Strategy is called by its context, many times. Command is created now and run later, once.
StrategyCommand
Answershow should this task be done?what should be done, and when?
Holdsan algorithm (often stateless)a request: receiver + arguments (+ undo state)
Calledby its context, whenever it needs it, often many timesby an invoker, usually once, maybe later
Typical extrasswapping at run timeundo, redo, queues, logs, macros

They even work together. A command can use a strategy inside, to decide how to do its job (an ExportReport command that writes with a CsvFormat strategy). But the command is the request, and the strategy is just one of its tools. And commands also travel well: a command object can be passed down a Chain of Responsibility until a handler knows how to run it.

Strategy is how. Command is what, and when.

When to use it (and when not to)

Use it when:

  • ✓ you need undo and redo,
  • ✓ actions should be queued, scheduled, or retried,
  • ✓ you want a log to audit or replay,
  • ✓ many entry points (buttons, menus, shortcuts, scripts) trigger the same actions.

Skip it when:

  • ✗ it’s a one-off call with none of those needs: just call the method,
  • ✗ the action is tiny: a lambda (Runnable, Consumer) is already a tiny command,
  • ✗ you’d keep an unbounded history: cap its size, because every command in it stays in memory.

Watch out for undo of actions with outside effects (emails, payments): you can only compensate.

Decision flowchart: if the action needs undo, a queue, retries, a log or replay, use command objects; if not but many entry points trigger it, a shared command or action object still helps; otherwise just call the method, or pass a lambda. Decision flowchart: if the action needs undo, a queue, retries, a log or replay, use command objects; if not but many entry points trigger it, a shared command or action object still helps; otherwise just call the method, or pass a lambda.
When turning a call into an object pays for itself.

Recap

Direct calls are done and forgotten. Instead, wrap each request in a command, with execute and undo. Invokers only call execute. And a history of objects gives you undo, redo, macros, and queues.

Recap chain: direct calls are done and forgotten; a Command with execute and undo replaces them; invokers only call execute; a history of command objects gives undo, redo, macros and queues. Recap chain: direct calls are done and forgotten; a Command with execute and undo replaces them; invokers only call execute; a history of command objects gives undo, redo, macros and queues.
Turn the call into an object.
  • A command packs a request: its receiver, its arguments, and what it needs to undo.
  • The invoker triggers it without knowing the work; the client creates it.
  • Two stacks give you undo and redo; a list of commands is a macro.
  • Queued or logged commands are jobs and audit trails; outside effects need compensation.
  • Strategy is how. Command is what, and when.

Turn the call into an object.

Complete code

For reference, the whole editor history with a tiny document, written out so it compiles (Java 21):

import java.util.*;

record Range(int start, int end) { }
enum Style { PLAIN, ITALIC, BOLD }

class Document {
    private final StringBuilder text = new StringBuilder();
    private final Map<Range, Style> styles = new HashMap<>();

    void insert(int position, String s) { text.insert(position, s); }
    void delete(int position, int length) { text.delete(position, position + length); }
    Style styleAt(Range r) { return styles.getOrDefault(r, Style.PLAIN); }
    void bold(Range r) { styles.put(r, Style.BOLD); }
    void setStyle(Range r, Style s) { styles.put(r, s); }
    public String toString() { return text + " " + styles; }
}

interface Command {
    void execute();
    void undo();
}

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

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

    public void execute() { doc.insert(position, text); }
    public void undo()    { doc.delete(position, text.length()); }
}

class MakeBold implements Command {
    private final Document doc;
    private final Range range;
    private Style before;

    MakeBold(Document doc, Range range) { this.doc = doc; this.range = range; }

    public void execute() { before = doc.styleAt(range); doc.bold(range); }
    public void undo()    { doc.setStyle(range, before); }
}

class Macro implements Command {
    private final List<Command> steps;

    Macro(List<Command> steps) { this.steps = List.copyOf(steps); }

    public void execute() { steps.forEach(Command::execute); }
    public void undo()    { steps.reversed().forEach(Command::undo); }
}

class History {
    private final Deque<Command> done = new ArrayDeque<>();
    private final Deque<Command> undone = new ArrayDeque<>();

    void run(Command c) { c.execute(); done.push(c); undone.clear(); }

    void undo() {
        if (done.isEmpty()) return;
        Command c = done.pop();
        c.undo();
        undone.push(c);
    }

    void redo() {
        if (undone.isEmpty()) return;
        Command c = undone.pop();
        c.execute();
        done.push(c);
    }
}

public class Editor {
    public static void main(String[] args) {
        Document doc = new Document();
        History history = new History();

        history.run(new InsertText(doc, 0, "Hello"));
        history.run(new MakeBold(doc, new Range(0, 5)));
        history.run(new InsertText(doc, 5, " world"));
        System.out.println(doc);   // Hello world {Range[start=0, end=5]=BOLD}

        history.undo();            // removes " world"
        history.undo();            // bold off
        System.out.println(doc);   // Hello {Range[start=0, end=5]=PLAIN}

        history.redo();            // bold again
        System.out.println(doc);   // Hello {Range[start=0, end=5]=BOLD}
    }
}