Pattern Design Ultimate Design Pattern 2 — Questions and Answers
Question 1: Which design pattern ensures that a class has only one instance and provides a global access point to it?
- Prototype
- Singleton (Correct answer)
- Flyweight
- Multiton
Correct answer: Singleton
The Singleton pattern restricts instantiation of a class to a single object and provides a global access point via a static method.
Question 2: The Template Method pattern defines a skeleton of an algorithm in a base class and lets subclasses override specific steps. What is the key mechanism used?
- Interface delegation
- Inheritance and method overriding (Correct answer)
- Composition over inheritance
- Dynamic dispatch via strategy
Correct answer: Inheritance and method overriding
Template Method relies on inheritance, where the base class defines the algorithm structure and subclasses override hook or abstract methods.
Question 3: Which pattern converts the interface of a class into another interface that clients expect, allowing incompatible interfaces to work together?
- Bridge
- Decorator
- Adapter (Correct answer)
- Proxy
Correct answer: Adapter
The Adapter pattern wraps an existing class to make its interface compatible with a client's expected interface.
Question 4: In the Command pattern, what role does the 'Invoker' play?
- Implements the concrete action
- Stores and executes command objects (Correct answer)
- Defines the command interface
- Acts as the receiver of commands
Correct answer: Stores and executes command objects
The Invoker holds a command object and triggers its execute method, decoupling the sender from the receiver.
Question 5: Which structural pattern uses a tree structure to treat individual objects and compositions of objects uniformly?
- Decorator
- Composite (Correct answer)
- Chain of Responsibility
- Flyweight
Correct answer: Composite
The Composite pattern lets clients treat leaf nodes and composites the same way through a shared component interface.
Question 6: What is the primary intent of the Memento design pattern?
- Notify observers of state changes
- Capture and restore an object's internal state without exposing it (Correct answer)
- Define a family of algorithms
- Provide a simplified interface to a complex subsystem
Correct answer: Capture and restore an object's internal state without exposing it
Memento captures an object's state at a point in time so it can be restored later, without violating encapsulation.
Question 7: Which pattern provides a way to access elements of a collection sequentially without exposing the underlying data structure?
- Visitor
- Iterator (Correct answer)
- Composite
- Mediator
Correct answer: Iterator
The Iterator pattern abstracts traversal logic, letting clients iterate over a collection without knowing its internal structure.
Which design pattern ensures that a class has only one instance and provides a global access point to it?