Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 57 ยท Behavioral Patterns

Command

Learn the Command design pattern: turn a request into an object so you can undo it, redo it, queue it, log it and combine commands into macros.

The Command pattern turns a request into an object. Instead of calling editor.insert("hi") directly, you build a small object that says "insert hi at position 0" and that knows how to carry the action out. Because the request is now a thing you can hold, it can be stored, passed around, delayed, logged, repeated and, most usefully, undone.

Think of ordering food at a restaurant. You do not walk into the kitchen and cook. You write an order on a slip; a waiter carries it; the kitchen executes it later. The slip is a command: it separates the person who asks (the invoker) from the one who does the work (the receiver). Undo and redo in every editor you have used is built exactly this way.

A request as an object

Command Knows how to do an action, and how to undo it.
Receiver The object that actually does the work.
Invoker Triggers commands without knowing the details.

The invoker only needs to call execute.

1 / 2

The structure

The command interface has execute() and, if you want undo, undo(). A concrete command stores the receiver and the parameters of the request. The invoker holds commands and runs them.

classDiagram
    class Command {
        <<interface>>
        +execute()
        +undo()
    }
    class InsertText
    class DeleteRange
    class Editor
    class History
    Command <|.. InsertText
    Command <|.. DeleteRange
    InsertText --> Editor : acts on
    DeleteRange --> Editor : acts on
    History o--> Command : stack of

Commands talk to the receiver (the editor); the history only knows the Command interface.

A text editor with undo and redo

The text editor below is the receiver; it knows nothing about history. Each command remembers exactly what it needs to reverse itself. For Insert that is the position and the text. For Delete it must remember the deleted text, which it captures when it first runs.

The history keeps two stacks. Running a command pushes it on the undo stack and clears the redo stack, because a new action invalidates any "future" you undid.

JS Undo and redo with a command history

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that undo is the exact inverse of execute, and that Delete records state it needs only at execution time. The other approach, saving a full copy of the document before each command, is the job of the Memento pattern, which you will meet in Mediator and Memento. Commands that store only the change use less memory; snapshots are simpler to get right.

Macros: a command made of commands

Because a command is just an object with execute and undo, a group of commands can itself be a command. This is the Composite idea applied to commands, and it gives you macros, "replace all", and transactions for free. To undo a macro you undo its steps in reverse order.

JS A macro command and a command queue

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The Multiply command stores the old value instead of dividing, because multiplying by zero cannot be undone by dividing. Always check that your undo truly restores the state, whatever the inputs.

Queues, logs and retries

Once requests are objects, three more uses fall out:

  • Queues and schedulers. A job queue is a queue of commands. Worker threads or a scheduler call execute() later, possibly on another machine if the command can be serialized.
  • Logging and replay. Write each executed command to a log. After a crash, replay the log to rebuild the state. Databases and event-sourced systems do this.
  • Retries and transactions. If one command in a batch fails, call undo() on the ones that already ran.

Functions can also be commands. In JavaScript or Python a closure such as () => buffer.insertAt(0, "x") already packages a request. Use full command objects when you need extra abilities: an undo, a readable description, serialization, or a priority.

When to use it, and the costs

Use Command when you need to parameterize an object with an action, queue or schedule operations, support undo and redo, or keep an audit log. GUI toolkits use it for menu items and buttons, so one command can be wired to a menu entry, a toolbar icon and a keyboard shortcut at once.

The costs are one extra class per action and the burden of writing a correct undo. Commands that touch external systems (sending an email, charging a card) usually cannot be undone and need a compensating action instead, such as a refund.

Command is easy to confuse with Strategy: a strategy is how something is done and is chosen once, while a command is a request to do something, held until it is run. Compare also Observer, which broadcasts a change to many listeners, and Chain of Responsibility, which passes a request along until someone handles it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the Command pattern turn into an object?

    A command packages 'do this with these arguments' as an object, so it can be stored, passed around, delayed, logged and undone.
  2. 2. Which object in the text editor example actually changes the text?

    The receiver does the real work. Commands call its methods, and the History only stores and replays commands.
  3. 3. After you undo twice and then run a brand new command, what should happen to the redo stack?

    Redo only makes sense along the original timeline. A new command branches off it, so the old 'future' is discarded.
  4. 4. In what order should a macro undo its steps?

    Later steps may depend on earlier ones, so you must unwind them last-in, first-out.
  5. 5. Why does Multiply store the previous value instead of dividing by the factor on undo?

    Multiplying by 0 destroys the old value, so the command saves it to restore exactly. An undo must truly restore the state for every input.

Summary

  • Command wraps a request as an object with execute() and usually undo().
  • The invoker triggers commands without knowing what they do; the receiver does the work.
  • Undo and redo use two stacks; a new command clears the redo stack.
  • Commands can be grouped into macros, which undo their steps in reverse order.
  • The same idea powers job queues, logs and replay, and retries with rollback.
  • Closures can serve as simple commands; use objects when you need undo or descriptions.

Next lesson: State.