Skip to content
Tutorials Center
My learning

Topics

Lesson 147 of 171 ยท Modern C++ and Beyond

Design Patterns in C++

Learn the design patterns that matter in modern C++ - RAII, factory, builder, strategy, observer, CRTP, PIMPL and singleton - with runnable examples and their trade-offs.

A design pattern is a named, reusable answer to a problem that keeps showing up: "how do I create objects without hard-coding their types?", "how do I let other code react when something changes?", "how do I swap an algorithm at run time?". Knowing the names lets you talk about designs quickly ("the exporters come from a factory, and the UI observes the model"), and knowing the trade-offs keeps you from forcing a pattern where a plain function would do.

C++ changes the classic patterns in two ways. First, it has its own idioms that other languages don't need, above all RAII, CRTP and PIMPL. Second, modern C++ makes many textbook patterns much smaller: a strategy can be a lambda, a factory can be a map of functions, and an observer list can be a vector of std::function. This lesson walks through the patterns you'll meet most often in real C++ code, each with a runnable example and an honest note about when not to use it.

RAII: the pattern behind everything else

Resource Acquisition Is Initialization means: tie every resource (memory, file, lock, socket, transaction) to the lifetime of an object. The constructor acquires it, the destructor releases it, and C++ guarantees the destructor runs when the object goes out of scope, whether the function returns normally, returns early, or throws. You met it in Destructors and RAII; std::unique_ptr, std::vector, std::lock_guard and std::fstream are all RAII types.

A handy general-purpose RAII tool is a scope guard: an object that runs any action you give it when the scope ends, unless you cancel it. It's perfect for "undo this unless everything succeeds":

C++ A scope guard for rollback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Class template argument deduction works out F from the lambda, so you never spell its type. Every other pattern in this lesson leans on RAII: factories return std::unique_ptr, observers clean up with handles, and PIMPL owns its implementation through a smart pointer.

Factory: create objects without naming their types

A factory is a function (or object) that decides which concrete class to create and hands back a pointer to the base. Callers depend only on the interface, so you can add new implementations without touching them. In modern C++ a factory returns std::unique_ptr<Base>: the caller gets clear, exclusive ownership (see Abstract Classes and Interfaces).

When the choice comes from data (a config value, a file extension, a command name), a registry of creation functions beats a long if/else chain:

C++ A factory with a registry

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Adding XML support is one new class and one registry line. A function-local static is initialized the first time the function runs, thread-safely, so the registry has no global-initialization-order problems. Returning nullptr for unknown names is one choice; returning std::expected or throwing are others (see Error Handling Without Exceptions).

Don't build a factory when there's only one implementation and no realistic second one. auto exporter = CsvExporter{}; is simpler, faster and easier to read. Patterns are tools for flexibility you actually need.

Builder: step-by-step construction

A constructor with eight parameters is unreadable at the call site: Request("POST", url, true, false, 3000, ...). A builder collects the settings one named step at a time and produces the finished, validated object at the end. Each step returns *this, so calls chain (see The this Pointer).

C++ A fluent builder with validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The builder is worth it when construction has rules (like "GET has no body") or many optional parts. For a plain bag of settings, C++20 designated initializers on an aggregate give you named arguments with zero extra code:

C++
struct RetryPolicy {
    int attempts = 3;
    std::chrono::milliseconds delay{200};
    bool exponential = true;
};

RetryPolicy policy{.attempts = 5, .exponential = false};   // delay keeps its default

Designators must appear in declaration order, and any you skip keep their default member initializer (see Structs, Aggregates and Unions).

Strategy: swap an algorithm

The strategy pattern makes one step of an algorithm replaceable: how to price an order, how to compare items, how to retry. C++ gives you three ways to do it, and each has its place:

Approach How Chosen Cost
Virtual interface class Pricing { virtual double price(...) = 0; } at run time virtual call, heap object usually
std::function a member std::function<double(double)> at run time possible allocation, indirect call
Template parameter template <typename Pricing> class Checkout at compile time none, but each choice is a new type

std::function is often the sweet spot: any lambda, function or functor with the right signature fits, and no class hierarchy is needed.

C++ Strategy with std::function and with a template

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The standard library itself is full of compile-time strategies: the comparator of std::sort and std::map, the hash of std::unordered_map, the deleter of std::unique_ptr. Prefer the template form when the strategy is fixed at compile time and speed matters; choose std::function or a virtual interface when you need to store different strategies in one variable or change them at run time (see Function Objects and std::function).

Observer: notify interested parties

The observer pattern lets an object (the subject) announce events to any number of listeners without knowing who they are. GUIs, game engines and model/view code use it constantly, usually under the names signals and slots, events or callbacks. A small, type-safe version is a list of std::function objects plus a way to unsubscribe:

C++ A tiny signal with subscribe and unsubscribe

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The classic observer bug is a dangling listener: an object subscribes, gets destroyed, and the subject calls into freed memory. Two defenses appear above: explicit disconnect with an id, and capturing a std::weak_ptr so the slot checks whether its target still exists (see Smart Pointers: shared_ptr and weak_ptr). Production libraries go one step further and return an RAII connection object that disconnects in its destructor. Also beware of listeners that connect or disconnect while emit is iterating: erasing the current element of the map invalidates the loop's iterator. Robust signals copy the slot list before calling it, or defer changes until the emit finishes.

CRTP: static polymorphism

The Curiously Recurring Template Pattern looks odd at first: a class derives from a template instantiated with itself, class Square : public Shape<Square>. The base knows the exact derived type at compile time, so it can call derived functions with a static_cast and no virtual call. You get reuse of base code with zero runtime cost and full inlining. CRTP is also the standard way to write mixins, small bases that add a feature to whatever class uses them.

C++ CRTP and its C++23 replacement, deducing this

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Because Counted<Enemy> and Counted<Bullet> are different classes, each has its own alive_: that's the whole trick. The price of CRTP is that Shape<Square> and Shape<Circle> have no common base, so you can't put them in one std::vector; when you need a heterogeneous collection, use virtual functions. In C++23, deducing this (this const auto& self, see The this Pointer) replaces many CRTP uses with clearer code; GCC 14+, Clang 18+ and recent MSVC support it.

PIMPL: hide the implementation

In C++, a class's private members live in its header, so every file that includes the header must be recompiled whenever a private detail changes, and it sees all the headers those members need. The PIMPL idiom ("pointer to implementation") moves the private data into a separate struct that's only declared in the header and defined in the .cpp file:

C++
// widget.h - what users see
#include <memory>
#include <string>

class Widget {
public:
    explicit Widget(std::string name);
    ~Widget();                              // defined in widget.cpp, where Impl is complete
    Widget(Widget&&) noexcept;
    Widget& operator=(Widget&&) noexcept;

    void click();
    int clicks() const;

private:
    struct Impl;                            // declared, not defined
    std::unique_ptr<Impl> impl_;
};
C++
// widget.cpp - free to change without recompiling users
#include "widget.h"
#include <vector>                           // heavy includes stay here

struct Widget::Impl {
    std::string name;
    std::vector<int> history;
};

Widget::Widget(std::string name) : impl_{std::make_unique<Impl>(std::move(name), std::vector<int>{})} {}
Widget::~Widget() = default;               // Impl is complete here, so unique_ptr can delete it
Widget::Widget(Widget&&) noexcept = default;
Widget& Widget::operator=(Widget&&) noexcept = default;

void Widget::click() { impl_->history.push_back(static_cast<int>(impl_->history.size()) + 1); }
int Widget::clicks() const { return static_cast<int>(impl_->history.size()); }

The destructor must be declared in the header and defined after Impl is complete; if you let the compiler generate it inline in the header, std::unique_ptr tries to delete an incomplete type and the build fails. Our editor compiles a single file, so this runnable version puts both halves in one file in the same order:

C++ PIMPL in one file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

sizeof(Widget) is one pointer (8 bytes on our server) no matter how many members Impl grows. That's also why PIMPL is how libraries keep a stable ABI: they can add private fields without changing the class layout users compiled against. The costs are one heap allocation per object and an extra indirection on every access. Copying needs hand-written copy operations that clone *impl_ (see Nested and Local Classes and Header Files and Multiple Source Files).

Singleton, and why to avoid it

A singleton is a class with exactly one instance and a global access point. In C++ the cleanest form is the "Meyers singleton": a function-local static, which is created on first use and initialized thread-safely since C++11.

C++ A singleton versus passing the dependency

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The singleton works, but it's a global variable in disguise. Every function can reach it without saying so, tests can't swap it out or reset it between runs, and destruction order at program exit is hard to reason about when singletons use each other. The alternative is plain dependency injection: create one object in main and pass a reference to the code that needs it, as parse_age does. Keep singletons for things that truly are one-per-process and stateless from the caller's view, and even then prefer a function returning a reference over a class with a static instance() and private constructor tricks.

Choosing a pattern

  • Start with the simplest code: values, functions and standard containers. Reach for a pattern when a real need appears (a second implementation, a run-time choice, a listener you don't know yet).
  • In C++ the "small" versions usually win: a lambda over a strategy class hierarchy, a registry map over a factory class, std::function slots over observer interfaces.
  • Use virtual interfaces when you need heterogeneous collections or plugins; use templates and CRTP when the choice is known at compile time and performance matters.
  • Every pattern still obeys ownership rules: return std::unique_ptr from factories, never store raw pointers to observers you don't own, and let destructors clean up.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the scope guard example, why does transfer(-5) print "rollback!" even though nothing calls the action explicitly?

    Leaving the scope by any path destroys local objects. The guard's destructor runs the action because active_ is still true; only the success path calls release().
  2. 2. Why does the PIMPL Widget declare its destructor in the class and define it after struct Impl?

    An inline, compiler-generated destructor would be instantiated where Impl is still incomplete, and unique_ptr's default deleter refuses to delete an incomplete type.
  3. 3. struct Enemy : Counted<Enemy> {}; and struct Bullet : Counted<Bullet> {}; With two Enemy and three Bullet objects alive, what does Enemy::alive() return?

    Counted<Enemy> and Counted<Bullet> are distinct classes, so each has its own static alive_ counter. Only the two Enemy objects incremented Counted<Enemy>'s counter.
  4. 4. A pricing strategy must be changeable at run time and stored in one member variable. Which option fits best?

    std::function can hold any callable with the right signature and be reassigned at run time. A template parameter fixes the strategy at compile time and makes each choice a different type.
  5. 5. What is the main design problem with a Logger singleton used inside many functions?

    Any function can reach the global instance without declaring it, so tests can't substitute or reset it. Passing the dependency in explicitly avoids that. (Function-local static initialization has been thread-safe since C++11.)

Summary

  • RAII ties resources to object lifetimes; a scope guard extends the idea to any "undo unless successful" action.
  • A factory returns std::unique_ptr<Base> and hides concrete types; a registry of creation functions handles data-driven choices.
  • A builder names each construction step and validates at the end; designated initializers cover simple option structs.
  • A strategy can be a virtual interface, a std::function or a template parameter: run-time flexibility versus zero overhead.
  • An observer list of std::function slots needs a way to unsubscribe and protection against dangling listeners (ids, RAII connections, weak_ptr).
  • CRTP gives static polymorphism and per-class mixins; C++23 deducing this replaces many uses.
  • PIMPL hides private members behind a pointer for faster builds and a stable ABI, at the cost of an allocation and an indirection.
  • A singleton is a global in disguise; prefer passing dependencies explicitly.

Next: Best Practices and Common Mistakes, a checklist of habits that keep C++ code correct, safe and readable.