Pattern Design Behavioral Design Patterns 1 — Questions and Answers
Question 1: Which behavioral pattern defines a one-to-many dependency so that when one object changes state, all dependents are notified automatically?
- Observer (Correct answer)
- Mediator
- Command
- Strategy
Correct answer: Observer
The Observer pattern establishes a subscription mechanism that notifies all registered observers whenever the subject's state changes.
Question 2: The Strategy pattern allows:
- Swapping algorithms at runtime without changing the client (Correct answer)
- Defining a skeleton algorithm with deferred steps
- Encapsulating requests as objects
- Traversing a collection without exposing its structure
Correct answer: Swapping algorithms at runtime without changing the client
Strategy defines a family of algorithms, encapsulates each one, and makes them interchangeable so the client can select the appropriate algorithm at runtime.
Question 3: The Command pattern encapsulates a request as an object primarily to support:
- Undo/redo, queuing, and logging of operations (Correct answer)
- State-based transitions
- Recursive tree traversal
- Simplified access to a subsystem
Correct answer: Undo/redo, queuing, and logging of operations
By encapsulating requests as Command objects, you can queue them, log them, and reverse them with an undo operation.
Question 4: Template Method pattern enforces an algorithm's structure by:
- Defining the skeleton in a base class with some steps deferred to subclasses (Correct answer)
- Delegating all steps to a strategy object
- Using chain of handlers for each step
- Storing state transitions in a state machine
Correct answer: Defining the skeleton in a base class with some steps deferred to subclasses
Template Method defines the overall algorithm in the parent class and lets subclasses override specific steps without changing the algorithm's structure.
Question 5: Which behavioral pattern is used to traverse elements of a collection without exposing the underlying representation?
- Iterator (Correct answer)
- Visitor
- Interpreter
- Memento
Correct answer: Iterator
The Iterator pattern provides a standard way to access elements of a collection sequentially without needing to know its internal structure.
Question 6: The Chain of Responsibility pattern passes a request along a chain until:
- A handler processes it or the chain ends (Correct answer)
- All handlers process it in sequence
- Only the first handler processes it
- The request is stored as a Command object
Correct answer: A handler processes it or the chain ends
Each handler in the chain either handles the request or passes it to the next handler, allowing dynamic assignment of responsibilities.
Which behavioral pattern defines a one-to-many dependency so that when one object changes state, all dependents are notified automatically?