Pattern Design Basic Design Pattern 2 — Questions and Answers
Question 1: Which design pattern ensures only one instance of a class is created throughout an application's lifetime?
- Factory
- Singleton (Correct answer)
- Prototype
- Builder
Correct answer: Singleton
The Singleton pattern restricts instantiation of a class to a single object, providing a global access point to it.
Question 2: What is the primary purpose of the Adapter pattern?
- Add new behaviors to an object at runtime
- Convert an interface into another that clients expect (Correct answer)
- Define a family of algorithms and make them interchangeable
- Compose objects into tree structures
Correct answer: Convert an interface into another that clients expect
The Adapter pattern acts as a bridge between two incompatible interfaces, enabling them to work together without modifying existing code.
Question 3: In which design pattern category does the Iterator pattern belong?
- Creational
- Structural
- Behavioral (Correct answer)
- Architectural
Correct answer: Behavioral
The Iterator pattern is behavioral because it defines how objects communicate and interact, specifically how to traverse a collection.
Question 4: The Composite pattern is best suited for representing which type of structure?
- A queue of tasks
- A part-whole hierarchy (Correct answer)
- A sequence of algorithm steps
- A chain of responsibility
Correct answer: A part-whole hierarchy
The Composite pattern lets clients treat individual objects and compositions uniformly, making it ideal for tree-like part-whole hierarchies.
Question 5: Which pattern defines a skeleton of an algorithm in a base class, deferring some steps to subclasses?
- Strategy
- Command
- Template Method (Correct answer)
- Chain of Responsibility
Correct answer: Template Method
The Template Method pattern defines an algorithm's structure in a superclass while allowing subclasses to override specific steps without changing the overall structure.
Question 6: Which design pattern is used when you want to provide a simplified interface to a complex subsystem?
- Proxy
- Flyweight
- Facade (Correct answer)
- Bridge
Correct answer: Facade
The Facade pattern provides a unified, simplified interface to a set of interfaces in a subsystem, reducing complexity for clients.
Question 7: What problem does the Flyweight pattern primarily solve?
- Ensuring thread safety in concurrent access
- Reducing memory usage by sharing common state among many objects (Correct answer)
- Decoupling an abstraction from its implementation
- Managing dependencies between objects
Correct answer: Reducing memory usage by sharing common state among many objects
The Flyweight pattern minimizes memory consumption by sharing as much data as possible with similar objects, using intrinsic (shared) and extrinsic (unique) state.
Which design pattern ensures only one instance of a class is created throughout an application's lifetime?