Command Pattern
Turn an action into an object, so it can be stored, queued, logged, undone and run by code that does not know what it does.
Overview
The Command pattern is one of the behavioral patterns in Design Patterns (Gamma, Helm, Johnson and Vlissides, 1994). A method call happens and is gone. A command is that call wrapped in an object: it holds the target, the arguments and an execute method. Because it is an object, it can be put in a list, sent across a queue, written to a log, run later, run again, or paired with an undo method that reverses it.
The pattern is behind undo and redo in every editor, behind job queues, and behind the way a toolbar button, a menu item and a keyboard shortcut all do the same thing. Interviewers ask about Command to see whether you can separate the thing that triggers an action from the thing that performs it, and whether you can build undo correctly, including the awkward cases: redo after a new action, and actions that must be grouped.
The problem it solves
A button needs to save the document. The simplest code puts document.save() in the button's click handler. Now the menu item needs the same, and the keyboard shortcut, and the auto-save timer. Each one calls the document directly, and the document must be reachable from all of them. Undo is impossible, because nothing remembers what was done.
Put the two designs side by side. With direct calls, the button knows the document and its methods; with Command, the button knows one thing, command.execute(). With direct calls, the same action is written in four places; with Command, one command object is bound to four triggers. Direct calls leave no record of what ran, while commands can be kept in a history, a queue or a log. And with direct calls, undo needs special code everywhere, while each command knows how to undo itself.
Interview questions
- How do you implement undo and redo, and what are the tricky cases?
- What is a macro command, and how does it relate to Composite?
- How does Command turn into a job queue?
- How is Command different from Strategy? Both wrap behavior in an object.
- Why should the invoker not know the receiver? Show the coupling and the fix.
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio