C++ Design Patterns: Singleton, Factory, Observer, Strategy & 12 More With Modern C++17/20 (2025)
âš¡ Quick Answer: Design Patterns in C++
- 23 GoF patterns — Creational, Structural, Behavioral categories
- Singleton — Meyer's static local: thread-safe since C++11, zero-overhead
- Factory — return
unique_ptr<Base>; decouple creation from use - Observer —
std::functioncallbacks: no virtual observer base class needed - Strategy — swap algorithms at runtime; enables Open/Closed Principle
- CRTP — static polymorphism: same flexibility as virtual, zero vtable overhead
- Rule — apply patterns when complexity justifies; don't over-engineer
Design patterns are the shared vocabulary of software engineering — knowing them lets you communicate design decisions in seconds and avoid reinventing solutions that were formalized 30 years ago. This guide covers all 23 GoF patterns in context and implements 12 of them in full modern C++17/20 with annotated code, output, and the "when to use" guidance that textbooks usually skip.
All 23 Patterns
Full GoF catalog
Creational
Singleton, Factory, Builder
Structural
Adapter, Decorator, Proxy
Behavioral
Observer, Strategy, Command
CRTP
Static polymorphism
Modern C++ Patterns
PIMPL, Policy, Type Erasure
Anti-patterns
What to avoid
FAQ / Interview
Top 10 questions
All 23 GoF Design Patterns — Quick Reference
| Pattern | Intent (one line) | Category | C++ feature |
|---|---|---|---|
| Singleton | Ensure one instance, global access | Creational | Static local var |
| Factory Method | Subclasses decide which class to instantiate | Creational | unique_ptr return |
| Abstract Factory | Create families of related objects | Creational | pure virtual factory |
| Builder | Construct complex objects step by step | Creational | Fluent API, *this |
| Prototype | Clone existing objects | Creational | virtual clone() |
| Adapter | Convert interface to another | Structural | Wrapping / MI |
| Bridge | Decouple abstraction from implementation | Structural | pImpl pointer |
| Composite | Tree structures of objects | Structural | vector<Component*> |
| Decorator | Add behavior by wrapping | Structural | RAII wrapper |
| Facade | Simplified interface to subsystem | Structural | Forwarding class |
| Flyweight | Share objects to reduce memory | Structural | shared_ptr cache |
| Proxy | Control access to an object | Structural | Same interface wrapper |
| Chain of Responsibility | Pass request along handler chain | Behavioral | Linked handlers |
| Command | Encapsulate action as object (undo/redo) | Behavioral | execute/undo methods |
| Iterator | Sequential access without exposing structure | Behavioral | STL iterators / ranges |
| Mediator | Centralize communication between objects | Behavioral | Event bus |
| Memento | Capture/restore object state | Behavioral | Snapshot struct |
| Observer | Notify dependents of state change | Behavioral | std::function vector |
| State | Change behavior when state changes | Behavioral | virtual state classes |
| Strategy | Swap interchangeable algorithms | Behavioral | std::function / vtable |
| Template Method | Define algorithm skeleton; subclasses fill steps | Behavioral | final + virtual hooks |
| Visitor | Add operations without modifying classes | Behavioral | std::variant + visit |
| Interpreter | Grammar for simple language | Behavioral | AST nodes |
Creational Patterns
#include <iostream>
#include <string>
using namespace std;
class Logger {
private:
Logger() = default; // private constructor
public:
// Delete copy and assignment — no second instance allowed
Logger(const Logger&) = delete;
Logger& operator=(const Logger&) = delete;
// Meyer's Singleton — static local init is thread-safe in C++11
static Logger& instance() {
static Logger inst; // initialized once, destroyed at exit
return inst;
}
void log(const string& msg) const {
cout << "[LOG] " << msg << endl;
}
};
int main() {
Logger::instance().log("Application started");
Logger::instance().log("Processing data");
// Same instance — address is identical
cout << (&Logger::instance() == &Logger::instance() ? "Same" : "Different") << endl;
return 0;
}
[LOG] Application started
[LOG] Processing data
Same#include <iostream>
#include <memory>
#include <string>
#include <stdexcept>
using namespace std;
// Abstract product
class Shape {
public:
virtual ~Shape() = default;
virtual void draw() const = 0;
virtual double area() const noexcept = 0;
};
class Circle : public Shape {
double r;
public:
explicit Circle(double radius) : r(radius) {}
void draw() const override { cout << "Circle(r=" << r << ")\n"; }
double area() const noexcept override { return 3.14159 * r * r; }
};
class Rectangle : public Shape {
double w, h;
public:
Rectangle(double w, double h) : w(w), h(h) {}
void draw() const override { cout << "Rectangle("<<w<<"x"<<h<<")\n"; }
double area() const noexcept override { return w * h; }
};
// Factory function — decouples creation from use
unique_ptr<Shape> createShape(const string& type) {
if (type == "circle") return make_unique<Circle>(5.0);
if (type == "rectangle") return make_unique<Rectangle>(4.0, 6.0);
throw invalid_argument("Unknown shape: " + type);
}
int main() {
for (const auto& type : {"circle", "rectangle"}) {
auto s = createShape(type);
s->draw();
cout << " Area: " << s->area() << "\n";
}
return 0;
}
Circle(r=5)
Area: 78.5398
Rectangle(4x6)
Area: 24#include <iostream>
#include <memory>
using namespace std;
// Abstract products
class Button { public: virtual void render() const = 0; virtual~Button()=default; };
class Checkbox{ public: virtual void render() const = 0; virtual~Checkbox()=default;};
// Windows products
class WinButton : public Button { public: void render() const override { cout << "[WinButton]\n"; } };
class WinCheckbox: public Checkbox { public: void render() const override { cout << "[WinCheckbox]\n"; } };
// Mac products
class MacButton : public Button { public: void render() const override { cout << "[MacButton]\n"; } };
class MacCheckbox: public Checkbox { public: void render() const override { cout << "[MacCheckbox]\n"; } };
// Abstract Factory
class UIFactory {
public:
virtual unique_ptr<Button> createButton() = 0;
virtual unique_ptr<Checkbox> createCheckbox() = 0;
virtual~UIFactory() = default;
};
class WinFactory : public UIFactory {
public:
unique_ptr<Button> createButton() override { return make_unique<WinButton>(); }
unique_ptr<Checkbox> createCheckbox() override { return make_unique<WinCheckbox>(); }
};
class MacFactory : public UIFactory {
public:
unique_ptr<Button> createButton() override { return make_unique<MacButton>(); }
unique_ptr<Checkbox> createCheckbox() override { return make_unique<MacCheckbox>(); }
};
void renderUI(UIFactory& factory) {
auto btn = factory.createButton();
auto chk = factory.createCheckbox();
btn->render(); chk->render();
}
int main() {
WinFactory win; renderUI(win);
MacFactory mac; renderUI(mac);
}
[WinButton]
[WinCheckbox]
[MacButton]
[MacCheckbox]#include <iostream>
#include <string>
using namespace std;
struct ServerConfig {
string host = "localhost";
int port = 8080;
int timeout = 30;
bool useTLS = false;
string logLevel = "info";
};
class ServerConfigBuilder {
ServerConfig cfg;
public:
// Each setter returns *this — enables chaining
ServerConfigBuilder& host (string v) { cfg.host = move(v); return *this; }
ServerConfigBuilder& port (int v) { cfg.port = v; return *this; }
ServerConfigBuilder& timeout (int v) { cfg.timeout = v; return *this; }
ServerConfigBuilder& useTLS (bool v) { cfg.useTLS = v; return *this; }
ServerConfigBuilder& logLevel(string v) { cfg.logLevel = move(v); return *this; }
ServerConfig build() const { return cfg; }
};
int main() {
auto cfg = ServerConfigBuilder()
.host("api.example.com")
.port(443)
.useTLS(true)
.timeout(60)
.logLevel("debug")
.build();
cout << cfg.host << ":" << cfg.port
<< " TLS=" << cfg.useTLS
<< " log=" << cfg.logLevel << endl;
}
api.example.com:443 TLS=1 log=debugStructural Patterns: Adapter, Decorator, Proxy
Adapter — convert an incompatible interface
#include <iostream>
using namespace std;
// New interface clients expect
class ModernLogger {
public:
virtual ~ModernLogger() = default;
virtual void log(const string& msg) const = 0;
};
// Legacy system we cannot modify
class LegacyLogger {
public:
void writeLog(const char* text) {
cout << "[LEGACY] " << text << endl;
}
};
// Adapter: wraps Legacy, presents ModernLogger interface
class LoggerAdapter : public ModernLogger {
LegacyLogger legacy;
public:
void log(const string& msg) const override {
legacy.writeLog(msg.c_str()); // delegate + adapt
}
};
void processApp(ModernLogger& logger) {
logger.log("App started");
logger.log("Processing complete");
}
int main() {
LoggerAdapter adapter;
processApp(adapter); // uses legacy internally, modern interface externally
}
[LEGACY] App started
[LEGACY] Processing completeDecorator — stack optional behaviors
#include <iostream>
#include <memory>
using namespace std;
class Coffee {
public:
virtual ~Coffee() = default;
virtual string description() const = 0;
virtual double cost() const noexcept = 0;
};
class Espresso : public Coffee {
public:
string description() const override { return "Espresso"; }
double cost() const noexcept override { return 1.50; }
};
// Base decorator — holds and delegates to wrapped coffee
class CoffeeDecorator : public Coffee {
protected:
unique_ptr<Coffee> wrapped;
public:
explicit CoffeeDecorator(unique_ptr<Coffee> c) : wrapped(move(c)) {}
};
class MilkDecorator : public CoffeeDecorator {
public:
using CoffeeDecorator::CoffeeDecorator;
string description() const override { return wrapped->description() + ", Milk"; }
double cost() const noexcept override { return wrapped->cost() + 0.30; }
};
class SugarDecorator : public CoffeeDecorator {
public:
using CoffeeDecorator::CoffeeDecorator;
string description() const override { return wrapped->description() + ", Sugar"; }
double cost() const noexcept override { return wrapped->cost() + 0.10; }
};
int main() {
auto coffee = make_unique<Espresso>();
coffee = make_unique<MilkDecorator>(move(coffee));
coffee = make_unique<SugarDecorator>(move(coffee));
cout << coffee->description() << " → $" << coffee->cost() << endl;
}
Espresso, Milk, Sugar → $1.9Behavioral Patterns: Observer, Strategy, Command, Template Method
Observer — event notification with std::function
#include <iostream>
#include <vector>
#include <functional>
#include <string>
using namespace std;
class EventBus {
using Handler = function<void(string_view)>;
vector<Handler> handlers;
public:
// Attach any callable: lambda, function ptr, bound method
void on(Handler h) { handlers.push_back(move(h)); }
void emit(string_view event) {
for (const auto& h : handlers) h(event);
}
};
int main() {
EventBus bus;
// Observers are just lambdas — no base class required
bus.on([](string_view e){ cout << "Logger: " << e << "\n"; });
bus.on([](string_view e){ cout << "Analytics: " << e << "\n"; });
bus.on([](string_view e){ cout << "Audit: " << e << "\n"; });
bus.emit("user.login");
cout << "---\n";
bus.emit("order.placed");
}
Logger: user.login
Analytics: user.login
Audit: user.login
---
Logger: order.placed
Analytics: order.placed
Audit: order.placedStrategy — swappable algorithms
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
class Sorter {
using SortFn = function<void(vector<int>&)>;
SortFn strategy;
public:
explicit Sorter(SortFn fn) : strategy(move(fn)) {}
void setStrategy(SortFn fn) { strategy = move(fn); }
void sort(vector<int>& v) { strategy(v); }
};
// Strategies as simple lambdas or functions
auto ascending = [](auto& v){ sort(v.begin(), v.end()); };
auto descending = [](auto& v){ sort(v.rbegin(), v.rend()); };
auto byAbsVal = [](auto& v){ sort(v.begin(), v.end(), [](int a, int b){ return abs(a) < abs(b); }); };
int main() {
Sorter sorter(ascending);
vector<int> data = {3, -1, 4, -5, 2};
sorter.sort(data);
for (int x : data) cout << x << " "; cout << "\n";
sorter.setStrategy(descending);
sorter.sort(data);
for (int x : data) cout << x << " "; cout << "\n";
}
-5 -1 2 3 4
4 3 2 -1 -5 Command — undo/redo system
#include <iostream>
#include <memory>
#include <stack>
#include <string>
using namespace std;
class Command {
public:
virtual ~Command() = default;
virtual void execute() = 0;
virtual void undo() = 0;
};
class TextEditor {
string text;
public:
void append(string_view s) { text += string(s); }
void deleteChars(int n) { if (n <= (int)text.size()) text.erase(text.size()-n); }
void print() const { cout << "Text: '" << text << "'\n"; }
};
class AppendCommand : public Command {
TextEditor& editor; string added;
public:
AppendCommand(TextEditor& e, string_view s) : editor(e), added(s) {}
void execute() override { editor.append(added); }
void undo() override { editor.deleteChars(added.size()); }
};
class History {
stack<unique_ptr<Command>> history;
public:
void execute(unique_ptr<Command> cmd) {
cmd->execute();
history.push(move(cmd));
}
void undo() {
if (!history.empty()) { history.top()->undo(); history.pop(); }
}
};
int main() {
TextEditor ed; History hist;
hist.execute(make_unique<AppendCommand>(ed, "Hello"));
hist.execute(make_unique<AppendCommand>(ed, ", World"));
ed.print(); // Hello, World
hist.undo(); ed.print(); // Hello
hist.undo(); ed.print(); // (empty)
}
Text: 'Hello, World'
Text: 'Hello'
Text: ''CRTP — Zero-Cost Static Polymorphism
#include <iostream>
using namespace std;
// CRTP base: Derived is the template parameter
template<class Derived>
class Animal {
public:
// Non-virtual: dispatches at compile time via static_cast
void makeSound() {
static_cast<Derived*>(this)->sound(); // resolved at compile time
}
// Mixin: automatically available to all Animals
void describe() {
cout << "I am a " << static_cast<Derived*>(this)->name() << "\n";
makeSound();
}
};
class Dog : public Animal<Dog> {
public:
void sound() { cout << "Woof!\n"; }
string name() { return "Dog"; }
};
class Cat : public Animal<Cat> {
public:
void sound() { cout << "Meow!\n"; }
string name() { return "Cat"; }
};
// Template function — static dispatch, no virtual table
template<class T>
void greet(Animal<T>& a) { a.describe(); }
int main() {
Dog d; greet(d);
Cat c; greet(c);
// Zero vtable overhead — equivalent to direct function calls
}
I am a Dog
Woof!
I am a Cat
Meow!Modern C++ Patterns: PIMPL, Policy-Based Design, Type Erasure
// ── widget.h (public API — only forward declaration) ────────────
#pragma once
#include <memory>
#include <string>
class Widget {
public:
Widget(const std::string& name);
~Widget(); // defined in .cpp where Impl is complete
Widget(Widget&&) noexcept;
Widget& operator=(Widget&&) noexcept;
void render() const;
private:
struct Impl; // forward declaration only
std::unique_ptr<Impl> pImpl; // pointer — sizeof(Widget) never changes
};
// ── widget.cpp (implementation — hidden from header users) ───────
#include "widget.h"
#include <iostream>
struct Widget::Impl {
std::string name;
int renderCount = 0;
// Adding members here does NOT require recompiling widget.h users
};
Widget::Widget(const std::string& n) : pImpl(std::make_unique<Impl>()) {
pImpl->name = n;
}
Widget::~Widget() = default;
Widget::Widget(Widget&&) noexcept = default;
Widget& Widget::operator=(Widget&&) noexcept = default;
void Widget::render() const {
cout << "Rendering " << pImpl->name
<< " (count=" << ++pImpl->renderCount << ")\n";
}
Anti-Patterns — What to Avoid
| Anti-Pattern | Problem | Fix |
|---|---|---|
| God Class | One class does everything — impossible to test or maintain | Split into focused, single-responsibility classes |
| Singleton overuse | Hidden global state — breaks unit tests, hides dependencies | Prefer dependency injection |
| Deep inheritance (>3 levels) | Fragile Base Class — base change breaks all descendants | Favor composition; use CRTP or interfaces |
| Raw ownership pointers | Leaks, double-free, dangling — undefined behavior | Use unique_ptr / shared_ptr |
| Virtual everything | Unnecessary vtable overhead; signals poor design | Use final for non-polymorphic classes; prefer CRTP |
| Premature patterns | Over-engineered solution before complexity justifies it | Start simple; refactor toward patterns when needed |
| Mutable global state | Action-at-a-distance bugs, non-deterministic tests | Encapsulate in objects; inject where needed |
FAQ / Interview Questions
static Singleton& getInstance() { static Singleton instance; return instance; }. Since C++11, the standard guarantees that static local variable initialization is thread-safe (magic statics). The instance is initialized exactly once, on first call, without any explicit mutex. Mark the constructor private and delete copy/move operations to prevent additional instances.template<class D> class Base { void f() { static_cast<D*>(this)->impl(); } };. Use CRTP when: the concrete type is known at compile time, you're writing performance-critical inner loops, or implementing mixins (Comparable, Printable base classes). Use virtual when: types vary at runtime, you need to store heterogeneous objects in one container, or the overhead is negligible.struct Impl; unique_ptr<Impl> pImpl;. Benefits: (1) Compilation firewall — changing private members in Impl doesn't cause recompilation of all header users. (2) ABI stability — adding private members doesn't change the class's memory layout. (3) Clean public API — no implementation includes or private members visible in the header. Essential for library APIs and large projects where compile time matters.Master C++ design patterns with real projects
Structured lessons, 200+ exercises, completion certificate. Join 50,000+ students.
Related C++ Topics on CoodeVerse
Frequently asked questions
What are design patterns in C++?
Design patterns are proven, reusable solutions to recurring software design problems, formalized in the 1994 book 'Design Patterns' by the Gang of Four (Gamma, Helm, Johnson, Vlissides). They are not code snippets — they are templates for solving categories of problems. Three categories: Creational (how objects are created: Singleton, Factory, Builder, Prototype), Structural (how objects are composed: Adapter, Decorator, Proxy, Facade), Behavioral (how objects communicate: Observer, Strategy, Command, State). In C++, modern features (templates, lambdas, smart pointers) enable cleaner, type-safe implementations than the original C++98 examples.
How do you implement a thread-safe Singleton in modern C++?
Use Meyer's Singleton — a static local variable initialized on first call. Since C++11, static local variable initialization is guaranteed thread-safe by the standard (no locks needed). static Singleton& get instance() { static Singleton instance; return instance; } Block copy and assignment: Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; Mark the constructor private: private: Singleton() = default; This approach is zero-overhead in the common path (after first call), thread-safe, and leak-free (the static is destroyed at program exit).
What is the Factory Method pattern in C++?
The Factory Method defines an interface for creating an object but lets subclasses or a separate factory function decide which concrete class to instantiate. This decouples the creator from the concrete product. Modern C++ implementation: use unique_ptr<Product> as return type (ownership is explicit); use make_unique to allocate. std::unique_ptr<Product> Creator::factory method(string type) { if (type=='A') return make_unique<ProductA>(); if (type=='B') return make_unique<ProductB>(); throw invalid_argument('Unknown type'); } Use when: you don't know the exact class to instantiate until runtime, or you want to decouple object creation from object use.
What is the difference between Factory Method and Abstract Factory?
Factory Method creates one product via a virtual method in a class hierarchy — each subclass creates a different product. It's a single-product creational pattern. Abstract Factory creates a family of related products via multiple factory methods — all products from one factory are designed to work together. Example: a UIFactory abstract class with create button() and create checkbox() — windows uifactory returns Windows-style widgets, mac uifactory returns Mac-style widgets. Use Factory Method for single-product creation; use Abstract Factory when products come in families and must be consistent with each other.
How do you implement the Observer pattern in modern C++?
Modern C++ Observer uses std::function for type-erased callbacks instead of a virtual Observer base class. Subject holds std::vector<std::function<void(int)>> observers; attach(f) pushes a call back; notify(v) calls each. Usage: subject.attach([](int v){ cout << 'Observer 1: ' << v; }); subject.set value(42); Benefits over classic virtual observer: no observer base class needed, lambdas inline the logic, std::function accepts any callable (lambda, function pointer, bound method). For unsubscription, return a token (int index or a handle) from attach() and use it in detach(). For thread-safety, protect the observers vector with std::mutex.
What is the Strategy pattern and how does it differ from if/else chains?
The Strategy pattern encapsulates interchangeable algorithms in separate classes (or lambdas) and lets a Context switch between them at runtime. Without Strategy: void sort(vector<int>& v, string algo) { if (algo=='bubble') bubbleSort(v); else if (algo=='quick') quickSort(v); } — adding a new algorithm requires modifying this function. With Strategy: Context ctx; ctx.set strategy(make_unique<QuickSort>()); ctx.sort(v); — adding a new algorithm is a new class, no existing code changes. This is the Open/Closed Principle: open for extension, closed for modification. Modern alternative: std::function<void(vector<int>&)> strategy; — assign any callable as the strategy.
What is the Decorator pattern in C++ and when should I use it?
The Decorator pattern adds behavior to an object dynamically by wrapping it in another object that has the same interface. Unlike inheritance which adds behavior statically at compile time, Decorator adds it at runtime and can be stacked. Example: a Coffee interface, then espresso base, then MilkDecorator(coffee) that delegates to the wrapped coffee and adds milk behavior, then sugar decorator stacked on top. When to use: when you need to add optional features to objects (logging, caching, retry, encryption) without modifying the class and without exponential subclass explosion. Modern alternative: Decorator via lambda composition or middleware chains (common in web frameworks).
What is CRTP (Curiously Recurring Template Pattern) in C++?
CRTP is a C++ template idiom where a class inherits from a template instantiated with itself: template<class Derived> class Base { void interface() { static_cast<Derived*>(this)->implementation(); } }; class MyClass : public Base<MyClass> { void implementation() { ... } }; CRTP achieves static polymorphism — no virtual table, no runtime dispatch overhead. Benefits: zero-cost abstraction (same performance as non-polymorphic code), enables mixins (add methods to any class that inherits the template), enables compile-time checking. Common uses: SFINAE constraints, mixins (Comparable, print able), policy-based design. Prefer CRTP over virtual when performance is critical and the type is known at compile time.
What is the Builder pattern in C++ and how do I implement a fluent builder?
The Builder pattern separates complex object construction from its representation, especially when an object has many optional parameters. A fluent builder returns *this from each setter: class server config { int port; string host; int timeout; }; class Builder { public: Builder& set port(int p) { port=p; return *this; } Builder& set host(string h) { host=h; return *this; } server config build() { return server config{port, host, timeout}; } }; Usage: auto cfg = Builder().set port(8080).set host('localhost').build(); This is far cleaner than a constructor taking 8 parameters. Modern C++ alternative: designated initializers in C++20: server config cfg{.port=8080, .host='localhost'};
What is the Command pattern in C++ and how does it enable undo/redo?
The Command pattern encapsulates an operation as an object. Each command has execute() and undo() methods. A history stack records executed commands; undo pops the stack and calls undo(). class Command { public: virtual void execute() = 0; virtual void undo() = 0; }; class text editor { stack<unique_ptr<Command>> history; public: void run(unique_ptr<Command> cmd) { cmd->execute(); history.push(move(cmd)); } void undo() { if (!history.empty()) { history.top()->undo(); history.pop(); } } }; Command is also used for task queues, macro recording, and remote procedure calls — anywhere you need to decouple the invoker from the action.
What is the Adapter pattern in C++ and what problem does it solve?
The Adapter converts one interface into another that clients expect, enabling classes with incompatible interfaces to work together. Two forms: (1) Object Adapter: holds a reference/pointer to the adaptee and delegates: class new interface { virtual void request() = 0; }; class old code { void specific request() {} }; class Adapter : public new interface { old code old; public: void request() override { old.specific request(); } }; (2) Class Adapter via multiple inheritance: class Adapter : public new interface, private old code { void request() override { specific request(); } }; Use Adapter when integrating third-party libraries, legacy code, or external APIs that you cannot modify.
What is the Proxy pattern in C++ and what are its main types?
A Proxy wraps a real object and controls access to it. Four main types: (1) Virtual Proxy: delays expensive object creation until first use (lazy initialization). (2) Remote Proxy: represents an object in a different address space (RPC stub). (3) Protection Proxy: controls access based on permissions (auth check before forwarding). (4) Caching Proxy: caches results of expensive calls. All share the same interface as the real object. Implementation: class Proxy : public Subject { unique_ptr<real subject> real; public: void request() override { if (!real) real = make_unique<real subject>(); real->request(); } }; The Proxy is transparent to the client — it calls subject->request() regardless of whether it's a proxy or the real object.
What is the Template Method pattern in C++?
Template Method defines the skeleton of an algorithm in a base class and lets subclasses override specific steps without changing the algorithm's structure. The base class method is the template — it calls virtual 'hook' methods in order. class DataProcessor { public: final void process() { read data(); processData(); write output(); } protected: virtual void read data() = 0; virtual void processData() = 0; virtual void write output() = 0; }; class csv processor : public DataProcessor { void read data() override { /* read CSV */ } ... }; Mark the template method final so subclasses cannot override the over all algorithm — only the steps. Template Method is the OOP complement to functional composition.
What is the difference between Decorator and Inheritance in C++?
Inheritance adds behavior at compile time — it's static and baked into the type system. You must create new subclasses for every combination of features: CoffeeWithMilk, CoffeeWithSugar, CoffeeWithMilkAndSugar — exponential explosion. Decorator adds behavior at runtime by wrapping objects — you create MilkDecorator and sugar decorator separately and stack them: new sugar decorator(new MilkDecorator(new Espresso())). This is linear instead of exponential. Rule of thumb: use inheritance when the 'is-a' relationship is fundamental and fixed; use Decorator when features are optional and combinable.
What design patterns are most common in C++ interviews?
Most frequently asked C++ design pattern interview questions: (1) Singleton — implement thread-safe Meyer's Singleton. (2) Factory Method — create objects without specifying the class. (3) Observer — event notification system. (4) Strategy — swap algorithms at runtime. (5) Decorator — add behavior dynamically. (6) CRTP — static polymorphism pattern. (7) PIMPL (Pointer to Implementation) — hide implementation details. (8) Command — undo/redo. (9) Adapter — interface compatibility. (10) Builder — fluent construction. Interviewers often ask you to implement Singleton without a static local variable, or to extend the Observer pattern with thread-safety.
What is the PIMPL idiom in C++ and why is it used?
PIMPL (Pointer to Implementation, also called Cheshire Cat or d-pointer) hides implementation details behind a forward-declared pointer in the header. Header: class Widget { struct Impl; unique_ptr<Impl> pImpl; public: Widget(); ~Widget(); void draw(); }; Implementation: struct Widget::Impl { /* all private members and includes */ }; Benefits: (1) Compilation firewall — changing Impl internals doesn't cause recompilation of header users. (2) ABI stability — adding private members doesn't change the class layout. (3) Faster compile times in large projects. (4) Clean public API — no private implementation details visible in the header. Use in library APIs and any class where you want compile-time isolation.
How do C++ design patterns compare to Java design patterns?
C++ patterns differ due to language features: Singleton — Java uses synchronized methods for thread-safety; C++ uses static local variables (thread-safe since C++11, zero-overhead). Factory — Java returns interface references; C++ returns unique_ptr<Base> for explicit ownership. Observer — Java uses interface Observer; C++ uses std::function for type-erased callbacks (more flexible, no base class needed). Strategy — Java stores interface references; C++ can store std::function (any callable: lambda, fun ctor, free function). CRTP — C++ exclusive: Java has no templates for static polymorphism. General: C++ patterns often use templates and value semantics where Java uses inheritance and reference semantics.
What are anti-patterns in C++ design?
Common C++ anti-patterns to avoid: (1) God Class — one class that does everything; split into focused classes. (2) Singleton over use — Singletons are global state; prefer dependency injection. (3) Deep inheritance — more than 2-3 levels is usually a design smell; use composition. (4) Raw pointers for ownership — use unique_ptr/shared_ptr. (5) Premature pattern application — adding patterns before the need is clear; start simple and refactor when complexity justifies it. (6) Mutable global state — leads to action-at-a-distance bugs. (7) Virtual everything — not all classes need polymorphism; use final to signal classes not meant to be subclassed.
What is composition over inheritance in C++ design patterns?
Composition over inheritance means building complex behavior by combining simple objects (has-a) rather than extending class hierarchies (is-a). Why: (1) Inheritance creates tight coupling — a change in the base class affects all derived classes. (2) Deep hierarchies are fragile — the Fragile Base Class problem. (3) Composition is more flexible — you can change the composed object at runtime. Example: instead of class FlyingFish extends Fish, Swimming, Flying — use class Fish { unique_ptr<SwimBehavior> swim; unique_ptr<fly behavior> fly; } and inject behaviors. This is the Strategy pattern applied structurally and is central to SOLID design.
What are best practices for using design patterns in C++?
Top 8 C++ design pattern best practices: (1) Favor composition over inheritance. (2) Use smart pointers (unique_ptr/shared_ptr) — never raw new in pattern implementations. (3) Mark copy/assignment =delete for Singleton and non-copy able resources. (4) Use std::function instead of virtual observer base classes. (5) Apply const and noexcept where correct. (6) Use CRTP for zero-cost static polymorphism instead of virtual when runtime dispatch is not needed. (7) Write unit tests for each pattern in isolation. (8) Don't apply patterns preemptively — refactor toward patterns when complexity justifies it.