Command turns a request into an object. Instead of calling doc.insert("Hi") directly, you create a TypeText object that holds the document and the text, and hand it to whoever should run it. Because the request is now a value, it can be stored, queued, logged, sent elsewhere, run later, and, if it also knows how to reverse itself, undone and redone. It is the pattern behind undo stacks, menu and keyboard-shortcut actions, job queues and macro recorders.
Think of it like
An order ticket in a restaurant
A waiter does not cook. They write your order on a ticket and clip it to the kitchen rail. The ticket is the command: it says exactly what to make and for which table, and it can wait in line, be reordered, be handed to whichever cook is free, or be torn up if you change your mind. The waiter (the invoker) only knows how to pass tickets along; the cook (the receiver) knows how to make the dish. The pile of finished tickets is a log of everything the kitchen did that night.
The problem
A small text editor has a document (TextDoc) with insert(s) and delete(n). The Editor offers one method per kind of edit and calls the document directly. Users want undo, so before each edit the editor copies the whole text into a prev field, and undo() writes it back. This is the Before version in the visualizer above. It works for one undo; everything beyond that is where it breaks down.
class Editor {
private prev = ""; // snapshot for undo
constructor(private doc: TextDoc) {}
type(s: string): void {
this.prev = this.doc.getText();
this.doc.insert(s);
}
erase(n: number): void {
this.prev = this.doc.getText();
this.doc.delete(n);
}
undo(): void {
this.doc.setText(this.prev);
}
}
editor.type("Hi there");
editor.erase(6); // "Hi"
editor.undo(); // "Hi there"
editor.undo(); // still "Hi there": one level only- One level of undo, and no redo.
prevholds a single snapshot, so the second undo restores the same text again and changes nothing. Nothing remembers what was undone, so redo is impossible. - The receiver had to change for undo.
TextDocgrewgetText()andsetText()only so thatEditorcould copy and overwrite its whole state. - Duplicated bookkeeping. Every edit method starts with the same snapshot line. Forget it in a new method and undo silently restores the wrong text.
- Every new edit edits
Editor. Uppercase, indent, paste: each one is another method in the class that every keystroke goes through. - Requests cannot travel. A menu item, a toolbar button and a keyboard shortcut all need their own code to call
editor.erase(6). An edit cannot be put in a queue, written to a log, recorded into a macro or replayed, because it is a method call that is over as soon as it happens.
The pattern
Intent: encapsulate a request as an object, so that you can parameterize clients with different requests, queue or log requests, and support undoable operations. The Gang of Four book introduced it with this very kind of editor: menu items that each hold a command object (PasteCommand, OpenCommand, and a MacroCommand that runs a sequence of them), so the menu code never knows what a click will do.
- Command (
Command) - The interface every request implements: usually
execute(), andundo()when the requests must be reversible. It is all the invoker knows. - Concrete command (
TypeText,DeleteText) - One class per kind of request. It holds a reference to the receiver, the arguments (
text,n), and whatever it needs to undo itself (deleted).execute()calls the receiver;undo()reverses that. - Receiver (
TextDoc) - The object that does the real work. It knows how to insert and delete text and knows nothing about commands, menus or undo.
- Invoker (
Editor) - Triggers commands without knowing what they do. Here it calls
execute(), keeps every command it ran on an undo stack (undos) and moves them to a redo stack (redos) when they are undone. A button, a menu item, a job queue or a scheduler can be an invoker too. - Client
- Creates concrete commands, wires each to its receiver, and hands them to the invoker. Here, the client program at the bottom of the code panel.
The chain is client → invoker → command → receiver. The invoker and the receiver never meet: Editor has no field pointing at the document, and TextDoc has no idea an editor exists. The command object in between carries everything needed to perform the request later, which is what lets the invoker keep it, line it up, or run it backwards.
What the visualizer shows
Press Play in the visualizer at the top of the page, or step with the arrow buttons. It really runs the classes in the code panel and draws what happened; the caption under the stage explains every step.
- Class diagram:
EditorholdsCommands (the aggregation marked0..*) but has no line toTextDoc; only the concrete commands do. Wheneditorcallsexecute()orundo(),Commandturns violet (the interface that declares the method) and the implements line of the command that actually runs lights up. - Objects at runtime:
editorshows its two stacks as lists of references,undos = [type, del]andredos = [], with an arrow from each stack to every command on it. Each command shows its own data:typekeepstext = "Hi there", anddelkeepsn = 6and, once it has run,deleted = " there". Watchdoc.textgo from"Hi there"to"Hi"and back. - Sequence of calls: every edit is the same three hops,
editor→ command →doc, and back. The client never callsdocitself. - Before / With Command and Add uppercase: the toggle switches to the snapshot version, where the second
undo()visibly changes nothing. Add uppercase applies the change request to whichever version is shown; touched classes get a badge (new class, oredited +6 −0), and the Change request panel beside the code compares both versions. On a phone the three views sit behind a Classes / Objects / Sequence switch.
Walkthrough
- 1
Create the receiver and the invoker
With With Command selected, the client creates
doc(text = "") andeditor, whose two stacks start empty:undos = [],redos = [].editorholds no reference todoc. - 2
Turn the first edit into an object
new TypeText(doc, "Hi there")createstype. Nothing has been typed yet: the request is just data, a receiver plus the text to insert. - 3
Run it
editor.run(type)callstype.execute(), which callsdoc.insert("Hi there"). Back inrun(), the editor pushes the command:undos = [type]. - 4
Run a second command
The client creates
del = new DeleteText(doc, 6)and runs it.del.execute()callsdoc.delete(6), which returns" there", anddelstores it indeleted.doc.textis now"Hi"andundos = [type, del], newest last. - 5
Undo
editor.undo()pops the newest command,del, and pushes it ontoredos(undos = [type],redos = [del]). Then it callsdel.undo(), which inserts the saved" there".doc.textis"Hi there"again. - 6
What comes next
Another
undo()would poptypeand call itsundo(), which deletes 8 characters.redo()would pop fromredosand callexecute()again. The run stops here to keep it short, but the code panel shows both methods and the implementation below runs them. - 7
Compare with Before
Switch to Before: the editor copies the text into
prevbefore each edit. The firstundo()restores"Hi there"; the second restores the same snapshot again, so the typing can never be undone. - 8
Add uppercase (change request)
With Add uppercase applied, the second command is
up = new UpperCase(doc, 5):doc.textbecomes"Hi THERE", andundo()restores"Hi there"from theoldtext the command saved.EditorandTextDocare the same code as before.
Before and after
Without the pattern
Editorcalls the document directly, one method per edit- Undo copies the whole text before every edit
- One level of undo, no redo
TextDocneedsgetText()/setText()just for undo- A new edit is a new method in
Editor - Simple to read for two or three edits
With Command
Editoronly callsexecute()andundo()onCommand- Each command stores just what it needs to reverse itself
- Unlimited undo and redo: two stacks of objects
TextDockeeps its plain editing API- A new edit is a new class;
Editoris untouched - One class per edit, and undo logic to test for each
| Change request: add an uppercase edit, with undo | Before | With Command |
|---|---|---|
| Existing classes edited | 1 (Editor) | 0 |
| New classes | 0 | 1 (UpperCase) |
| Lines changed in existing classes | 6 (+6 −0) | 0 |
| Classes touched | 1 | 1 |
Both versions touch one class, so the count alone does not pick a winner. The difference is which class. Before, the six new lines go into Editor, the class every edit runs through, and they have to repeat the snapshot line or undo breaks. With Command, Editor and the existing commands are not opened at all: the new behavior arrives as a new class that implements the same two methods, and undo and redo work for it immediately. The Before version also still has only one level of undo after the change; fixing that would mean a list of snapshots in Editor, which is a third rewrite of the same class.
Variations
Two ways to undo: inverse operation or stored state
| Strategy | How undo() works | Example | Trade-off |
|---|---|---|---|
| Inverse operation | Apply the opposite operation using the command's own arguments | TypeText deletes text.length characters; Move(dx, dy) moves by (-dx, -dy) | Tiny, but only possible when an exact inverse exists |
| Store what the operation destroyed | execute() saves the part it overwrites; undo() puts it back | DeleteText keeps deleted; UpperCase keeps old (uppercase has no inverse: "Hi" and "HI" both become "HI") | Costs memory per command; the data must be captured when execute() runs, not when the command is created |
| Snapshot the whole receiver | Save the receiver's entire state before executing; undo restores it | A Memento per command, or per checkpoint | Simple and always correct, but expensive for large state; often combined with commands (snapshot every 50 commands, replay the rest) |
The redo stack, and why a new command clears it
Undo moves a command from undos to redos; redo moves it back and calls execute() again. A new command clears redos, as run() does. The commands on the redo stack were recorded against a document state that no longer exists. Undo "delete the last 6 characters" on "Hi there", then type "!": redoing the delete now removes "there!" and leaves "Hi ", a text that never existed in either history. Linear undo therefore throws that future away. Some editors keep it instead: Vim stores an undo tree whose branches you can walk with g- and g+, and Emacs records undos as ordinary changes, so undo itself can be undone. Real undo stacks usually add three refinements:
- Merge small commands. Typing "hello" should undo as one step, not five. A command can offer to absorb the next one of the same kind (Qt's
QUndoCommand::mergeWith()does this for commands with the sameid()). - Cap the history. Each command holds data, so long sessions need a limit on the number of commands (or their total size); the oldest are dropped.
- Remember the saved point. Marking the position in the stack where the file was last saved tells you whether the document is "dirty" after any mix of undos and redos (Qt's
QUndoStack::setClean()/isClean()).
Macro commands
A macro is a command made of commands, which makes it an application of Composite: execute() runs every step in order, undo() undoes them in reverse order. The invoker cannot tell a macro from a single command, so one undo reverts the whole group. The same idea gives you grouped edits ("Replace all" as one undo step) and recorded macros (capture the commands a user runs, replay them later). If step 3 of 5 throws, the first two have already changed the receiver, so a robust macro catches the failure, undoes the completed steps in reverse and rethrows: a small transaction.
class Macro implements Command {
constructor(private steps: Command[]) {}
execute(): void {
for (const step of this.steps) step.execute();
}
undo(): void {
// last step first
for (const step of [...this.steps].reverse()) step.undo();
}
}
editor.run(new Macro([new TypeText(doc, "!"), new TypeText(doc, "!")]));
editor.undo(); // removes both "!"Queues, logs and replay
- Queue it and run it later. Undo is only one reason to make a request a value. Thread pools, job queues and schedulers accept command objects and run them later, on another thread or a pool of workers. The second implementation below is a job queue with retries. Across processes the command becomes a message on a broker (see Message Queues & Pub/Sub); a retried command must then be safe to run twice, which is what Idempotent Receiver is about.
- Log it. Writing every command to an append-only log gives you an audit trail, and replaying the log rebuilds the state after a crash. Databases do this at a lower level: many write each change to a write-ahead log before applying it, and recovery uses the log to redo committed changes (and, in some designs, to undo unfinished ones).
- Make the log the source of truth. Event Sourcing stores the changes instead of the current state. It logs events (facts that happened, such as
TextDeleted) rather than commands (requests that may still be rejected), but the replay idea is the same. - Undo across services. A distributed transaction cannot simply be rolled back, so a Saga pairs each step with a compensating action, the network version of
undo().
Commands as functions and closures
In languages with first-class functions, the simplest command is a closure: () => doc.insert("Hi") captures its receiver and arguments just like TypeText does. Java's Runnable, a Python callable and a C++ std::function are all one-method command interfaces, and passing a lambda to a thread pool is the Command pattern with no extra classes. That is the right choice when you only need to run the request later. What a bare function loses:
- Undo. A closure has one entry point. You can pair two closures (
{ execute, undo }), but then you are writing command objects again. - Serialization. A closure cannot be written to disk or sent to another process;
{ type: "delete", n: 6 }can. Persistent logs, job queues that survive restarts and remote execution all need commands as data. - Identity and introspection. You cannot show a closure in a history menu ("Undo Delete"), merge two of them, or check what it will do. A command object can carry a name, a timestamp and its arguments.
In real code
| Where | The command | What it buys |
|---|---|---|
| Java executors | Runnable and Callable<T> passed to Executor.execute() / ExecutorService.submit() | The task is run later on a pool thread; submit() returns a Future for the result |
| Python | Any callable passed to concurrent.futures.Executor.submit(fn, *args) | Same idea: the function and its arguments are packaged and run by a worker |
| Swing | javax.swing.Action (usually AbstractAction) shared by a menu item, a toolbar button and a key binding; UndoableEdit objects kept by an UndoManager | One object defines the label, icon, enabled state and behavior for every control that triggers it; undo() / redo() on the manager walk the edit history |
| Qt | QUndoCommand subclasses pushed onto a QUndoStack; QAction for menus and toolbars | push() calls the command's redo() to perform it; the stack handles undo, redo, merging, macros (beginMacro()) and the clean state |
| VS Code | Commands registered under string ids with vscode.commands.registerCommand(id, handler) | The Command Palette, menus and keybindings refer to the id, and extensions call executeCommand(id, ...args) |
| Redux | Actions: plain, serializable objects such as { type: "todos/added", payload } passed to dispatch() | Actions can be logged, replayed and inspected; Redux DevTools uses this for time-travel debugging |
| Databases | Records in a transaction or write-ahead log describing each change | Crash recovery replays the log; replication ships it to other servers |
When to use it, and when not to
Reach for Command when
- You need undo and redo, or a visible history of actions
- The same action is triggered from several places (menu, toolbar, shortcut, script)
- Requests must be queued, scheduled, retried or run on another thread
- Requests must be logged, audited or replayed
- Users should be able to record and replay macros
Think twice when
- You just need to call a method now: a direct call is clearer
- Only deferred execution is needed: a lambda is enough
- The action has external effects that cannot be reversed (an email was sent); plan a compensating action, not an
undo() - Every command would be a one-line wrapper around one receiver method, with no undo or queueing to justify it
Command vs similar patterns
| Pattern | The object represents | Key question it answers | Typical setting |
|---|---|---|---|
| Command | One request, with its receiver and arguments | What should be done, and can it be run later or reversed? | Undo stacks, menus and shortcuts, job queues |
| Strategy | An interchangeable algorithm | How should this be done? | Payment methods, sorting, pricing rules |
| Memento | A snapshot of another object's state | What did it look like before? | Undo by restoring state; often stored inside a command |
| Chain of Responsibility | A handler in a line of handlers | Who should handle this request? | Middleware, approval chains, UI event bubbling |
| Observer | A subscriber to events | Who wants to know that something happened? | Notifications, data binding |
| Composite | A tree of objects treated as one | How do I treat a group like a single item? | Macro commands, UI trees, file systems |
Implementation
The scenario as a complete program: a TextDoc receiver, a Command interface with execute and undo, TypeText (undo by inverse operation), DeleteText and UpperCase (undo by storing what was overwritten), a Macro command built from other commands, and an Editor invoker with an undo stack and a redo stack. The demo types, deletes, undoes twice, redoes once, shows that running a new command clears the redo stack, and undoes a two-step macro with a single undo.
from abc import ABC, abstractmethod
class TextDoc:
"""The receiver: it knows how to edit text, and nothing about undo."""
def __init__(self) -> None:
self._text = ""
def insert(self, s: str) -> None:
self._text += s
def delete(self, n: int) -> str:
"""Removes up to n characters from the end and returns them."""
end = max(0, len(self._text) - n)
cut = self._text[end:]
self._text = self._text[:end]
return cut
def __str__(self) -> str:
return self._text
class Command(ABC):
@abstractmethod
def execute(self) -> None: ...
@abstractmethod
def undo(self) -> None: ...
class TypeText(Command):
def __init__(self, doc: TextDoc, text: str) -> None:
self._doc = doc
self._text = text
def execute(self) -> None:
self._doc.insert(self._text)
def undo(self) -> None:
# Inverse operation: remove what was typed.
self._doc.delete(len(self._text))
class DeleteText(Command):
def __init__(self, doc: TextDoc, n: int) -> None:
self._doc = doc
self._n = n
self._deleted = ""
def execute(self) -> None:
# Captured when it runs, not when it is created.
self._deleted = self._doc.delete(self._n)
def undo(self) -> None:
self._doc.insert(self._deleted)
# The change request: one new class, no existing class edited.
class UpperCase(Command):
def __init__(self, doc: TextDoc, n: int) -> None:
self._doc = doc
self._n = n
self._old = ""
def execute(self) -> None:
# Uppercase has no inverse, so keep the previous state.
self._old = self._doc.delete(self._n)
self._doc.insert(self._old.upper())
def undo(self) -> None:
self._doc.delete(len(self._old))
self._doc.insert(self._old)
class Macro(Command):
"""A macro is a command made of commands (Composite)."""
def __init__(self, *steps: Command) -> None:
self._steps = list(steps)
def execute(self) -> None:
for step in self._steps:
step.execute()
def undo(self) -> None:
# Undo in reverse order: last step first.
for step in reversed(self._steps):
step.undo()
class Editor:
"""The invoker: it runs, undoes and redoes commands without
knowing what any of them does."""
def __init__(self) -> None:
self._undos: list[Command] = []
self._redos: list[Command] = []
def run(self, cmd: Command) -> None:
cmd.execute()
self._undos.append(cmd)
self._redos.clear() # a new edit makes the old "future" invalid
def undo(self) -> bool:
if not self._undos:
return False
cmd = self._undos.pop()
self._redos.append(cmd)
cmd.undo()
return True
def redo(self) -> bool:
if not self._redos:
return False
cmd = self._redos.pop()
self._undos.append(cmd)
cmd.execute()
return True
if __name__ == "__main__":
doc = TextDoc()
editor = Editor()
def show(step: str) -> None:
print(f'{step}: "{doc}"')
editor.run(TypeText(doc, "Hi there"))
editor.run(DeleteText(doc, 6))
show("type, delete") # "Hi"
editor.undo()
show("undo") # "Hi there"
editor.undo()
show("undo") # ""
editor.redo()
show("redo") # "Hi there"
editor.run(UpperCase(doc, 5)) # clears the redo stack
show("uppercase") # "Hi THERE"
print("redo possible?", editor.redo()) # False
editor.run(Macro(TypeText(doc, "!"), TypeText(doc, "!")))
show("macro") # "Hi THERE!!"
editor.undo() # one undo reverts the whole macro
show("undo") # "Hi THERE"
editor.undo()
show("undo") # "Hi there"Key takeaways
- Command turns a request into an object with
execute()(and usuallyundo()): a receiver plus the arguments, packaged so it can be run later, elsewhere, repeatedly or in reverse. - Four roles: the client builds the command, the invoker runs it without knowing what it does, the command calls the receiver, and the receiver does the work. In the visualizer
Editornever touchesTextDoc. - Undo and redo are two stacks of command objects: undo pops from one, pushes onto the other and calls
undo(); a new command clears the redo stack. - Each command undoes itself either by an inverse operation (
TypeText) or by storing what it overwrote (DeleteText,UpperCase); whole-state snapshots are the Memento alternative. - For the "add uppercase" request, With Command adds one class and edits none; without it
Editorgains 6 lines and still has one level of undo. - Queues, logs, retries and macros fall out of the same idea. A plain closure is enough when you only need deferred execution, but it gives up undo, naming and serialization.
Common pitfalls
- Capturing undo data at the wrong time:
DeleteTextmust record the removed text whenexecute()runs, not in its constructor, because the document may change between creation and execution. - An
undo()that is not an exact inverse: deletingncharacters when fewer existed, or lowercasing to undo an uppercase (it destroys the original capitals). An almost-right undo is worse than none, because the document drifts further from the truth with every undo and redo. Store what you overwrote, and test thatexecute()thenundo()restores exactly the previous state for every command. - Forgetting to clear the redo stack when a new command runs, so redo replays a command against a document it was never meant for.
- Unbounded history: every command keeps its receiver and its saved data alive. Cap the stack, merge small commands, and avoid storing whole snapshots in every command.
- Retrying commands that are not idempotent: a queued
ChargeCardthat timed out after charging will charge twice on retry. Give commands an id and make the receiver ignore duplicates.
Interview tips
- In LLD rounds that mention undo (text editor, drawing app, spreadsheet, smart-home remote), introduce a
Commandinterface withexecute()andundo()early, then an invoker with two stacks; walk through undo, redo and why a new command clears redo. - Name the four roles (client, invoker, command, receiver) on your diagram, and point out that the invoker depends only on the interface, so adding a command never edits it.
- Expect "Command vs Strategy" (what vs how) and "how would you persist or distribute this?" (serialize commands as data, put them on a queue, make handlers idempotent; mention event sourcing and CQRS, and that a CQRS command is a message, not a GoF command).
Real-world applications
- Undo and redo in editors, drawing tools, IDEs and spreadsheets.
- UI actions shared by menus, toolbars, keyboard shortcuts and command palettes (Swing
Action, QtQAction, VS Code commands). - Thread pools, schedulers and background job queues that run tasks later or elsewhere, with retries.
- Macro recording and scripted automation: record a list of commands, replay it.
- Transaction and audit logs, and state rebuilt by replaying a log (Redux action logs, write-ahead logs, event sourcing).
- Remote controls and device APIs: each button bound to a command object that can be reassigned at runtime.
Test yourself
In the visualizer, undos is [type, del] and the client calls editor.undo(). What does Editor do?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.