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.
Three actions, then three undos, in reverse order:
To undo, queue or replay an action, the program needs the action as a thing, not as a call that already happened.
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 request that’s written down can be stored, passed on, and reversed.
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.
And to be fair, it works. For a small app, it’s fine. But notice that the same call already lives in three places.
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.
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.
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:
| 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.
Turn the call into an object.
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); }
}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.)
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.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);
}
}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.
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.)
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.
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.
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 failureJava 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, elsewhereNotice 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 often gets confused with the Strategy pattern. Both put behavior behind an interface, and the class diagrams look alike.
| 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 until a
handler knows how to run it.
Strategy is how. Command is what, and when.
Use it when:
Skip it when:
Runnable, Consumer) is already a tiny command,Watch out for undo of actions with outside effects (emails, payments): you can only compensate.
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.
Turn the call into an object.
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}
}
}