Command

Intermediate · 16 min read · Low-Level Design, Behavioral Patterns

Requests as objects: queues, undo/redo, macros and audit logs.

The idea in plain words

Turn an action into an object. Once "type the word Hello" is an object, you can keep it in a list, run it later, send it to another thread, log it, or undo it.

The problem

A text editor has buttons, menu items and keyboard shortcuts that all trigger operations like "bold", "paste", "delete line". If each UI element calls the editor directly, the same logic is duplicated across invokers, and features like undo, macro recording or "repeat last action" have nothing to hold on to — an…

The solution

Wrap each operation in an object with an execute() method. The object stores the receiver (the thing that does the real work) and the parameters. Invokers (buttons, shortcuts, schedulers) only know the Command interface.

Undo/redo

Two strategies for undo:

Other uses

Runnable and Callable are commands: executor.submit(task) decouples what runs from when/where it runs. Job queues, cron schedulers and retry queues all store command objects.

Where you've seen it

Pros and cons

Comparisons

Interview questions

  • How would you implement undo/redo in a drawing application?
  • How do Runnable and an ExecutorService illustrate the Command pattern?

Further reading

Key takeaways

  • Command wraps a request (receiver + parameters) into an object with execute().
  • It decouples who triggers an action from who performs it.
  • Enables undo/redo (inverse ops or mementos), queues, scheduling, macros and audit logs.
  • Runnable/Callable and task queues are everyday commands.

Previous: State · Next: Chain of Responsibility