You need to design a system where user actions can be executed, undone, and redone, while also supporting queuing of requests and logging of all operations. Which design approach best fits this requirement to ensure loose coupling between the invoker and the receiver and to enable undo/redo functionality?
AImplementing the Command Pattern where each action is encapsulated as an object with execute and undo methods, and the invoker manages undo and redo stacks.
BUsing a simple function call approach where each action directly modifies the receiver's state without encapsulation.
CApplying a greedy algorithm that chooses the next best action to execute without storing history.
DUsing a dynamic programming approach to store all possible states and transitions for undo/redo.
Step-by-Step Solution
Solution:
Step 1: Identify the need for encapsulation of actions
The problem requires actions to be undoable and redoable, which demands encapsulating each action's execution and reversal logic.
Step 2: Recognize the pattern that supports undo/redo and request queuing
The Command Pattern encapsulates requests as objects, allowing the invoker to queue, log, and manage undo/redo stacks independently from the receiver.
Final Answer:
Option A -> Option A
Quick Check:
Command Pattern enables undo/redo with encapsulated commands [OK]
Quick Trick:Undo/redo needs encapsulated commands, not direct calls [OK]
Common Mistakes:
MISTAKES
Thinking direct function calls can support undo/redo cleanly
Confusing Command Pattern with greedy or DP algorithms
Trap Explanation:
PITFALL
Greedy and DP approaches do not inherently support undo/redo or decoupling of invoker and receiver, making them plausible but incorrect.
Interviewer Note:
CONTEXT
Tests if candidate understands why Command Pattern suits undo/redo and request queuing scenarios.