Bird
Raised Fist0

Which modification to the invoker's undo/redo management is necessary to handle this scenario without corrupting state?

hard🎤 Interviewer Follow-up Q15 of Q15
OOP & Design Patterns - Command Pattern - Undo/Redo, Request Queuing & Logging
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:
  1. 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.
  2. 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.
  3. Step 3: Confirm undo/redo stack integrity

    This approach preserves correct ordering and state consistency during undo/redo operations.
  4. Final Answer:

    Option C -> Option C
  5. 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.
Master "Command Pattern - Undo/Redo, Request Queuing & Logging" in OOP & Design Patterns

2 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More OOP & Design Patterns Quizzes