Design Patterns interview question · Most asked
How would you implement undo/redo with the Command pattern?
Summary
Make each action an object with execute() and undo() that stores what it needs to reverse itself. An invoker runs commands and pushes them on a history stack; undo pops and calls undo() (moving the command to a redo stack); any new command clears the redo stack.
Longer Answer
The invoker never knows what a command does, so new actions (bold, paste) are new command classes. Commands are also how job queues work (a serialised command run later by a worker), and how macros and audit logs are built.
For actions with external side effects (an email, a card charge), "undo" means a compensating action (a correction, a refund), not restoring previous state.
Key Points
- Command = action as an object with execute/undo.
- History stack for undo, redo stack for redo.
- New command clears redo.
- External side effects need compensating actions.
Deep dive: Design Patterns, Explained Simply: Command
Explanation
What interviewers look for
Correct stack mechanics and the external-side-effect caveat.
Follow-up questions
- When would you use Memento instead?
- How do background job queues relate to Command?
More most-asked Design Patterns questions
- What problem does the Builder pattern solve? Show an example.
- Explain the SOLID principles.
- What is a design pattern, and why are they useful?
- What is the difference between dependency inversion, dependency injection and inversion of control?
- Why is composition often preferred over inheritance?
- What is dependency injection, and what forms does it take?
- Explain the Factory Method pattern and how it differs from a simple factory.
- How do you implement a Singleton, and why is it often considered an anti-pattern?