In what situations would you use the Command pattern, such as in undo/redo operations?

The Command pattern fits any situation where an action needs to be represented as a first-class object that can be stored, passed around, queued, or reversed, rather than executed immediately and forgotten. Undo/redo is the most common example, but it's far from the only one.

Key Points: • Undo/redo systems store executed commands and call an undo() method to reverse them in order. • Task scheduling and job queues benefit from commands since they can be created now and executed later. • Logging and auditing become straightforward, since each command object naturally represents "what happened." • Macro recording works by capturing a sequence of commands and replaying them later. • GUI actions (button clicks, menu items) can all bind to Command objects instead of hardcoded handler logic.

Example: A text editor can push each edit as a Command onto an undo stack; calling undo() pops the last command and calls its reverse() method to restore the previous text state.

Interview Tip: A concise interview answer is:

"I'd reach for Command whenever an action needs to exist as an object rather than just happen immediately — undo/redo is the classic case, where each command stores enough state to reverse itself. It's equally useful for task queues, scheduling, and logging, anywhere you need to decouple 'what to do' from 'when and how many times to do it.'"