Pattern Design Behavioral Design Patterns 3 — Questions and Answers
Question 1: Which behavioral pattern is best suited for implementing a redo/undo history with multiple levels?
- Command + Memento (Correct answer)
- Observer + State
- Strategy + Template Method
- Visitor + Iterator
Correct answer: Command + Memento
Command stores each operation as an executable/undoable object, while Memento captures state snapshots, together enabling full undo/redo history.
Question 2: The Template Method pattern uses ________ while the Strategy pattern uses ________.
- Inheritance; composition (Correct answer)
- Composition; inheritance
- Aggregation; delegation
- Polymorphism; encapsulation
Correct answer: Inheritance; composition
Template Method relies on subclasses overriding inherited steps (inheritance), while Strategy injects different algorithm objects (composition).
Question 3: In the Mediator pattern, a potential drawback is:
- The mediator can become a God object that is too complex (Correct answer)
- Components become tightly coupled to each other
- Observers receive stale data
- State transitions become unpredictable
Correct answer: The mediator can become a God object that is too complex
Because all communication flows through it, the mediator can accumulate too much responsibility and become a maintenance bottleneck.
Question 4: The Visitor pattern's 'double dispatch' mechanism involves:
- Calling accept() on the element which calls the visitor's method back (Correct answer)
- Two sequential strategy selections
- Dispatching events to two observer lists
- Routing through two mediators
Correct answer: Calling accept() on the element which calls the visitor's method back
Double dispatch resolves the correct visitor method by first calling accept(visitor) on the element, which then calls the appropriate visit(element) on the visitor.
Question 5: Which pattern allows the same collection to be traversed with different algorithms without changing the collection?
- Iterator (Correct answer)
- Visitor
- Strategy
- Chain of Responsibility
Correct answer: Iterator
The Iterator pattern abstracts the traversal mechanism so different iterators (e.g., depth-first, breadth-first) can walk the same collection.
Question 6: State pattern and Strategy pattern are structurally similar but differ in that:
- State transitions are controlled internally; strategies are selected externally by the client (Correct answer)
- Strategy objects hold references to each other; state objects do not
- State encapsulates algorithms; strategy encapsulates state data
- Strategy uses inheritance; state uses composition
Correct answer: State transitions are controlled internally; strategies are selected externally by the client
In State, the object changes its own state based on conditions; in Strategy, the client decides which algorithm to inject.
Which behavioral pattern is best suited for implementing a redo/undo history with multiple levels?