Suppose you want to extend the Command Pattern to support commands that can be executed multiple times (reused) and also support undo/redo correctly. Which modification to the invoker's undo/redo management is necessary to handle this scenario without corrupting state?
AStore only one instance of each command and reuse it for all executions, pushing it multiple times onto undo stack.
BClear both undo and redo stacks after every command execution to avoid reuse issues.
CCreate a new command instance for each execution and push that instance onto the undo stack, ensuring undo/redo operate on the correct state snapshot.
DAvoid using undo/redo stacks and instead recompute state from scratch on each undo or redo.
Step-by-Step Solution
Solution:
Step 1: Understand reuse implications
Reusing the same command instance for multiple executions causes undo/redo to affect the wrong state because the command's internal state may change.
Step 2: Identify correct approach
Creating a new command instance per execution ensures each undo/redo corresponds to the exact executed command instance and its parameters.
Step 3: Confirm undo/redo stack integrity
This approach preserves correct ordering and state consistency during undo/redo operations.
Final Answer:
Option C -> Option C
Quick Check:
New instances per execution prevent state corruption on undo/redo [OK]
Quick Trick:Each execution needs a fresh command instance for correct undo/redo [OK]
Common Mistakes:
MISTAKES
Reusing command instances causing incorrect undos
Clearing stacks unnecessarily losing history
Trap Explanation:
PITFALL
Reusing instances looks efficient but breaks undo/redo correctness; clearing stacks loses history unnecessarily.
Interviewer Note:
CONTEXT
Tests candidate's understanding of command instance lifecycle and undo/redo correctness under reuse.