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

← All Design Patterns questions