Command
Turn a request into an object with everything needed to run it, so you can queue it, log it, retry it or undo it.
Description
A command object captures one action: what to do, on what, with which arguments, behind a tiny interface like execute() and often undo(). The code that triggers it, the invoker (a button, a keyboard shortcut, a job runner), doesn't know what the action does.
Because actions are now objects, you can keep them in a list. That gives you undo and redo, a log of what happened, retries, macros that replay several commands, and work queues that run commands later or elsewhere.
Class diagram
Command pattern class diagram
- Class CommandHistory with + run(command), + undo(), + redo().
- Interface Command with + execute(): void, + undo(): void.
- Class AddItem with + execute(), + undo().
- Class Cart with + add(sku, qty), + remove(sku, qty).
- CommandHistory stores Command.
- AddItem implements Command.
- AddItem acts on Cart.
Sequence diagram
Command pattern sequence diagram
- UI → CommandHistory: run(new AddItem(cart, mug, 2)).
- CommandHistory → AddItem(mug, 2): execute().
- AddItem(mug, 2) → Cart: add("mug", 2).
- CommandHistory → CommandHistory: push to done.
- UI → CommandHistory: undo().
- CommandHistory → AddItem(mug, 2): undo().
- AddItem(mug, 2) → Cart: remove("mug", 2).
- CommandHistory → CommandHistory: move to undone.
TypeScript example
Cart actions as command objects. CommandHistory runs them and keeps two stacks, which is all undo and redo need.
// Command: cart actions become objects, so they can be undone and redone.
class Cart {
readonly items = new Map<string, number>();
add(sku: string, qty: number): void {
this.items.set(sku, (this.items.get(sku) ?? 0) + qty);
}
remove(sku: string, qty: number): void {
const left = (this.items.get(sku) ?? 0) - qty;
if (left > 0) this.items.set(sku, left);
else this.items.delete(sku);
}
toString(): string {
return [...this.items].map(([sku, qty]) => `${qty}× ${sku}`).join(", ") || "(empty)";
}
}
// Command interface: everything needed to run and reverse one action
interface Command {
readonly label: string;
execute(): void;
undo(): void;
}
class AddItem implements Command {
readonly label: string;
private readonly cart: Cart;
private readonly sku: string;
private readonly qty: number;
constructor(cart: Cart, sku: string, qty: number) {
this.cart = cart;
this.sku = sku;
this.qty = qty;
this.label = `add ${qty}× ${sku}`;
}
execute(): void {
this.cart.add(this.sku, this.qty);
}
undo(): void {
this.cart.remove(this.sku, this.qty);
}
}
// Invoker: runs commands and keeps the history
class CommandHistory {
private readonly done: Command[] = [];
private readonly undone: Command[] = [];
run(command: Command): void {
command.execute();
this.done.push(command);
this.undone.length = 0; // a new action clears the redo stack
}
undo(): string {
const c = this.done.pop();
if (!c) return "nothing to undo";
c.undo();
this.undone.push(c);
return `undid ${c.label}`;
}
redo(): string {
const c = this.undone.pop();
if (!c) return "nothing to redo";
c.execute();
this.done.push(c);
return `redid ${c.label}`;
}
}
export function demo(): string[] {
const cart = new Cart();
const history = new CommandHistory();
history.run(new AddItem(cart, "mug", 2));
history.run(new AddItem(cart, "pen", 3));
const lines = [`cart: ${cart}`];
lines.push(history.undo(), `cart: ${cart}`);
lines.push(history.redo(), `cart: ${cart}`);
return lines;
}When to use it
Use it when
- You need undo/redo, such as in editors, design tools or forms with multiple steps.
- Actions should be queued, scheduled, retried or run in the background.
- You want an audit log of user actions that can be replayed.
- The same action is triggered from several places (a menu, a shortcut, a toolbar), and you want one implementation.
Avoid it when
- An action is simple, runs once and never needs undo, logging or queuing. A function call is clearer.
- Undo is easier to implement by restoring a snapshot of state. Use Memento instead of writing an inverse for every command.
Pitfalls
- Undo that doesn't truly reverse the action, for example removing items that existed before. Test each command's undo against its execute.
- Commands holding references to objects that change or disappear before the command runs. Capture what you need at creation time.
- Forgetting to clear the redo stack after a new action, which leads to confusing histories.
- One class per tiny action creates lots of boilerplate. Small commands can be plain objects with two functions.
Alternatives
Memento
Choose it when undo means "go back to how it was"; snapshots are simpler than inverse operations.
Strategy
Choose it when you're choosing how to do something, not recording what was done.
Chain of Responsibility
Choose it when requests need to find their handler along a chain.
Event Sourcing
Choose it when you want every change stored as a durable event, across a whole system.