Design Patterns in C++
Prerequisites: Interfacing with C
The same patterns covered for Java reappear in C++, expressed through smart pointers and RAII instead of garbage collection:
// Singleton, using a function-local static (thread-safe since C++11)
class AppConfig {
public:
static AppConfig &getInstance() {
static AppConfig instance;
return instance;
}
private:
AppConfig() = default;
};
// Factory, returning ownership via unique_ptr
std::unique_ptr<Shape> createShape(const std::string &kind) {
if (kind == "circle") return std::make_unique<Circle>(1.0);
throw std::invalid_argument("Unknown shape: " + kind);
}
Returning std::unique_ptr<Shape> from the factory makes ownership
explicit in the type signature itself — the caller receives sole
ownership, with no separate documentation needed to say so.