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?
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:
Step 1: Trace execution of first AddCommand(5)
Receiver state changes from 0 to 5 and prints "Receiver state changed to 5".
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".
Final Answer:
Option B -> Option B
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