Pattern Design Basic Design Pattern 3 — Questions and Answers
Question 1: In the Observer pattern, what are the two main roles?
- Publisher and Subscriber
- Subject and Observer (Correct answer)
- Producer and Consumer
- Sender and Receiver
Correct answer: Subject and Observer
The Observer pattern defines a Subject that maintains a list of Observers and notifies them automatically when its state changes.
Question 2: Which pattern allows you to add responsibilities to objects dynamically without modifying their class?
- Adapter
- Bridge
- Decorator (Correct answer)
- Composite
Correct answer: Decorator
The Decorator pattern wraps an object in decorator objects to attach new behaviors at runtime, as a flexible alternative to subclassing.
Question 3: The Command pattern converts requests into objects primarily to support which feature?
- Object pooling
- Lazy initialization
- Undo/redo operations (Correct answer)
- Thread synchronization
Correct answer: Undo/redo operations
Encapsulating requests as Command objects allows you to parameterize, queue, log, and reverse operations, making undo/redo straightforward to implement.
Question 4: Which design pattern uses a 'virtual' object as a placeholder to control access to another object?
- Decorator
- Proxy (Correct answer)
- Facade
- Adapter
Correct answer: Proxy
The Proxy pattern provides a surrogate or placeholder for another object to control access, add logging, or perform lazy initialization.
Question 5: What distinguishes a class-based (compile-time) Adapter from an object-based (runtime) Adapter?
- Class Adapter uses composition; object Adapter uses inheritance
- Class Adapter uses multiple inheritance; object Adapter uses composition (Correct answer)
- Class Adapter is faster; object Adapter is more flexible
- Class Adapter wraps interfaces; object Adapter wraps classes
Correct answer: Class Adapter uses multiple inheritance; object Adapter uses composition
A class Adapter inherits from both the target and adaptee (requiring multiple inheritance), while an object Adapter holds a reference to the adaptee via composition.
Question 6: In the State pattern, what determines which behavior an object exhibits?
- The object's class hierarchy
- The current value of a state variable
- The current State object the context holds (Correct answer)
- The sequence of method calls made on it
Correct answer: The current State object the context holds
The State pattern delegates behavior to a State object; when the context's state changes, it swaps the State object, altering its behavior.
Question 7: Which creational pattern separates the construction of a complex object from its representation?
- Abstract Factory
- Prototype
- Builder (Correct answer)
- Singleton
Correct answer: Builder
The Builder pattern uses a builder object to construct a complex product step by step, allowing the same construction process to create different representations.
In the Observer pattern, what are the two main roles?