# Command PatternHow 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*.

{{< lesson-video youtube="LP09to20trc" title="Command Pattern" >}}

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:

```mermaid {alt="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." caption="Undo walks back through the actions in reverse. The editor must have kept them."}
stateDiagram-v2
  Empty --> Hello: insert "Hello"
  Hello --> BoldHello: make it bold
  BoldHello --> HelloWorld: insert " world"
  HelloWorld --> BoldHello: Ctrl+Z
  BoldHello --> Hello: Ctrl+Z
  Hello --> Empty: Ctrl+Z
  class Hello c1
  class BoldHello c4
  class HelloWorld c1
```

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.

```mermaid {alt="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." caption="Once a request is written down, it can be stored, passed on and reversed."}
flowchart LR
  C["to-do card<br/>front: do it<br/>back: undo it"] --> Q["wait in a tray<br/>= a queue"]
  C --> L["be filed<br/>= a log"]
  C --> A["picked up by anyone<br/>= the invoker"]
  C --> M["clipped together<br/>= a macro"]
  C --> U["flipped over<br/>= undo"]
  class C hl
  class Q,A c6
  class L c2
  class M c5
  class U c3
```

> 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:

```java
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.

```mermaid {alt="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." caption="When the call happens on the spot, nothing remembers it."}
flowchart LR
  B["BoldButton"] -->|"bold(selection)"| D["Document"]
  M["BoldMenuItem"] -->|"bold(selection)"| D
  K["Ctrl+B"] -->|"bold(selection)"| D
  Z["Ctrl+Z"] -.->|"undo... what?"| X["nothing recorded"]
  class B,M,K c6
  class D c2
  class Z,X bad
```

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.

```mermaid {alt="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." caption="Five features, one missing ingredient."}
flowchart LR
  U["undo"] --> N(["the action, kept as data"])
  R["redo"] --> N
  P["repeat last action"] --> N
  M["record a macro"] --> N
  L["run it later"] --> N
  N -.-> X["direct calls:<br/>gone once they return"]
  class N hl
  class X bad
```

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](/code-smells/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:

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

That gives us four roles:

| Role | In the editor | Knows |
|---|---|---|
| **Receiver** | `Document` | how to do the real work (`insert`, `bold`, `setStyle`) |
| **Command** | `MakeBold`, `InsertText` | its receiver and its arguments: everything needed to run the request later |
| **Invoker** | button, menu item, shortcut, `History` | only "some command"; it calls `execute` |
| **Client** | the code that wires the editor | creates the command and hands it to the invoker |

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

```mermaid {alt="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." caption="The invoker knows only the interface; the command knows the receiver."}
classDiagram
  class Client
  class Button {
    -Command command
    +click()
  }
  class Command {
    <<interface>>
    +execute()
    +undo()
  }
  class MakeBold {
    -Document doc
    -Range range
    -Style before
  }
  class InsertText {
    -Document doc
    -int position
    -String text
  }
  class Document {
    +insert(int, String)
    +delete(int, int)
    +bold(Range)
    +setStyle(Range, Style)
  }
  Client ..> MakeBold : creates
  Client ..> Button : hands the command to
  Button o--> Command
  Command <|.. MakeBold
  Command <|.. InsertText
  MakeBold --> Document : receiver
  InsertText --> Document : receiver
```

```mermaid {alt="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." caption="Created now, triggered later, by an invoker that doesn't know the work."}
sequenceDiagram
  participant C as Client
  participant B as Button (invoker)
  participant M as MakeBold (command)
  participant D as Document (receiver)
  C->>M: new MakeBold(doc, range)
  C->>B: here is your command
  Note over B: later: the user clicks
  B->>M: execute()
  M->>D: bold(range)
```

> **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.

```java
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.

```java
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); }
}
```

```mermaid {alt="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." caption="The command fills in the back of its own card while it works."}
sequenceDiagram
  participant H as History
  participant M as MakeBold
  participant D as Document
  H->>M: execute()
  M->>D: styleAt(range)
  D-->>M: italic
  Note over M: before = italic
  M->>D: bold(range)
  H->>M: undo()
  M->>D: setStyle(range, italic)
```

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](/patterns/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.

```java
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);
    }
}
```

```mermaid {alt="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." caption="Undo and redo are just commands moving between two stacks."}
flowchart TD
  R(["run(c)"]) -->|"execute, push;<br/>clear undone"| DN["done stack<br/>InsertText, MakeBold"]
  DN -->|"undo: pop, c.undo()"| UN["undone stack"]
  UN -->|"redo: pop, c.execute()"| DN
  class R c6
  class DN,UN c3
```

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`:

```java
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.

```java
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.)

```mermaid {alt="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." caption="Last done, first undone."}
flowchart LR
  subgraph EX["execute(): in order"]
    direction TB
    E1["1. InsertText"] --> E2["2. MakeBold"] --> E3["3. Center"]
  end
  subgraph UN["undo(): in reverse"]
    direction TB
    U1["1. Center"] --> U2["2. MakeBold"] --> U3["3. InsertText"]
  end
  EX ~~~ UN
  class E1,U3 c1
  class E2,U2 c4
  class E3,U1 c5
```

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](/patterns/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.

```mermaid {alt="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." caption="A job is a command that waits for its turn."}
sequenceDiagram
  participant W as Web request
  participant Q as Job queue
  participant A as Worker 1
  participant B as Worker 2
  W->>Q: enqueue(SendInvoiceEmail)
  W-->>W: returns at once
  Q->>A: next job
  Note over A: mail server down
  A-->>Q: retry later
  Q->>B: same job, later
  Note over B: email sent
```

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):

```java
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.

```java
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](/patterns/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.

```mermaid {alt="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." caption="Strategy is called by its context, many times. Command is created now and run later, once."}
flowchart LR
  subgraph S["Strategy: how"]
    direction TB
    CTX["orders.sort(byTotal)"] -->|"compare() × many"| CMP["byTotal comparator"]
  end
  subgraph CM["Command: what, and when"]
    direction TB
    NEW["new MakeBold(doc, range)<br/>packed up now"] --> RUN["history.run(...)<br/>run later, once"]
    RUN --> UND["undo(), maybe"]
  end
  S ~~~ CM
  class CTX c6
  class CMP c1
  class NEW,RUN hl
  class UND c3
```

| | **Strategy** | **Command** |
|---|---|---|
| Answers | *how* should this task be done? | *what* should be done, and *when*? |
| Holds | an algorithm (often stateless) | a request: receiver + arguments (+ undo state) |
| Called | by its context, whenever it needs it, often many times | by an invoker, usually once, maybe later |
| Typical extras | swapping at run time | undo, 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](/patterns/chain-of-responsibility-pattern/) 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.

```mermaid {alt="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." caption="When turning a call into an object pays for itself."}
flowchart TD
  Q1{"Undo, queue, retry,<br/>log or replay?"}
  Q1 -->|yes| U["Command objects<br/>(with undo where possible)"]
  Q1 -->|no| Q2{"Many entry points<br/>trigger it?"}
  Q2 -->|yes| A["A shared command /<br/>action object"]
  Q2 -->|no| K["Just call the method<br/>(or pass a lambda)"]
  class U,A good
  class K muted
```

## 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.

```mermaid {alt="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." caption="Turn the call into an object."}
flowchart LR
  A["direct calls:<br/>done and forgotten"] --> B["Command:<br/>execute + undo"]
  B --> C["invokers only<br/>call execute"]
  C --> D["a history of objects:<br/>undo, redo, macros, queues"]
  class A bad
  class B hl
  class C c6
  class D good
```

- 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):

```java
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}
    }
}
```
