Bird
Raised Fist0

Given the following code snippet implementing the Command Pattern with undo/redo stacks, what will be the output after executing two AddCommands with values 5 and 3, then undoing one command?

easy🧾 Code Trace Q3 of Q15
OOP & Design Patterns - Command Pattern - Undo/Redo, Request Queuing & Logging
Given the following code snippet implementing the Command Pattern with undo/redo stacks, what will be the output after executing two AddCommands with values 5 and 3, then undoing one command?
AReceiver state changed to 5 Receiver state changed to 8 Receiver state reverted to 3
BReceiver state changed to 5 Receiver state changed to 8 Receiver state reverted to 5
CReceiver state changed to 5 Receiver state changed to 3 Receiver state reverted to 0
DReceiver state changed to 0 Receiver state changed to 3 Receiver state reverted to 5
Step-by-Step Solution
Solution:
  1. Step 1: Trace execution of first AddCommand(5)

    Receiver state changes from 0 to 5 and prints "Receiver state changed to 5".
  2. Step 2: Trace execution of second AddCommand(3) and undo

    State changes from 5 to 8, prints "Receiver state changed to 8". Undo reverts 3, state back to 5, prints "Receiver state reverted to 5".
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    State increments and decrements match commands executed and undone [OK]
Quick Trick: Undo reverts last command's effect on state [OK]
Common Mistakes:
MISTAKES
  • Forgetting to add command to undo stack
  • Undoing wrong command
Trap Explanation:
PITFALL
  • Candidates often confuse the order of execution and undo, leading to incorrect state values.
Interviewer Note:
CONTEXT
  • Tests ability to mentally execute command pattern code with undo/redo
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