CPP Design Patterns & Architecture 2 — Questions and Answers
Question 1: Which pattern ensures a class has only one instance and provides a global access point?
- Monostate
- Singleton (Correct answer)
- Registry
- Flyweight
Correct answer: Singleton
The Singleton pattern restricts instantiation of a class to one object and provides a static method to access it.
Question 2: In the Composite pattern, what role does the 'Leaf' class play?
- It manages child components
- It represents a container of components
- It is a primitive object with no children (Correct answer)
- It acts as the client interface
Correct answer: It is a primitive object with no children
A Leaf represents a basic element with no children, implementing the component interface directly.
Question 3: Which design pattern converts the interface of a class into another interface that clients expect?
- Bridge
- Decorator
- Adapter (Correct answer)
- Proxy
Correct answer: Adapter
The Adapter pattern wraps an existing class to make its interface compatible with another interface.
Question 4: What problem does the Chain of Responsibility pattern solve?
- Decoupling object creation from use
- Passing a request along a chain of handlers without knowing which will handle it (Correct answer)
- Ensuring only one handler processes each request
- Creating a hierarchy of command objects
Correct answer: Passing a request along a chain of handlers without knowing which will handle it
Chain of Responsibility lets handlers decide whether to process a request or pass it to the next handler in the chain.
Question 5: In C++, the 'std::function' combined with lambdas is most closely associated with which pattern?
- Strategy (Correct answer)
- Template Method
- Interpreter
- State
Correct answer: Strategy
The Strategy pattern defines a family of algorithms that can be swapped at runtime, matching how std::function holds interchangeable callables.
Question 6: Which pattern separates an abstraction from its implementation so both can vary independently?
- Adapter
- Bridge (Correct answer)
- Facade
- Proxy
Correct answer: Bridge
The Bridge pattern decouples abstraction and implementation by placing them in separate class hierarchies linked by composition.
Question 7: The Template Method pattern relies primarily on which C++ mechanism?
- Multiple inheritance
- Virtual functions and inheritance (Correct answer)
- Function pointers
- Templates and concepts
Correct answer: Virtual functions and inheritance
Template Method defines a skeleton algorithm in a base class using virtual functions that subclasses override to fill in steps.
Which pattern ensures a class has only one instance and provides a global access point?