Example demos

Runnable companions to the book.

Every pattern chapter has a demo behind it. Each demo is a self-contained, standalone-buildable CMake project with its own Conan recipe and a GoogleTest suite run through CTest, no containers. Read the matching chapter for context, then build the demo from its directory with the same local tools the prerequisites chapter installs.

Runnable examples

Each example makes a single pattern concrete and runnable with one command. Every card links to the demo's page on this site (a rendering of the README with cross-references), and each page links to the source on GitHub. Each demo also stands alone, so you can build it without reading the book first if you'd rather poke at it directly.

Chapter 3 · SOLID I

Invoicing: SRP, OCP, LSP

One Invoice type doing three jobs, split into focused responsibilities, extended through a rule abstraction without edits, and refined by a subtype that honors the base contract.

Read page →
Chapter 4 · SOLID II

Order notifications: ISP & DIP

A high-level policy depends on an abstraction, not a concrete gateway, and a fat interface is split into role interfaces each client depends on only where it needs them.

Read page →
Chapter 5 · RAII

Dock-bay lease: RAII

A scoped resource guard that acquires in the constructor and releases in the destructor, stays correct through exceptions and moves, plus a general-purpose scope guard.

Read page →
Chapter 6 · Ownership

Ownership: value, unique, shared, weak

A dispatch graph showing a Rule-of-Zero value type, sole ownership via unique_ptr, shared ownership via shared_ptr, and a weak_ptr that breaks a reference cycle.

Read page →
Chapter 7 · Testing

Quote intake: GoogleTest styles

Fixtures, parameterized tests, typed tests, GoogleMock interaction tests, and a death test, each used where it fits, all discovered and run through CTest.

Read page →
Chapter 8 · Strategy

Shipping-rate estimation

A checkout picks a carrier rate rule at runtime. The same pattern is shown three idiomatic ways: a virtual interface, a std::function, and a compile-time concept policy.

Read page →
Chapter 9 · Template Method

Order export: Template Method + NVI

A fixed export skeleton calls private virtual hooks in a set order; CSV, JSON, and EDI exporters override the hooks without touching the sequence or its invariants.

Read page →
Chapter 10 · State / FSM

Shipment lifecycle: four machines

The same shipment state rules as a GoF State pattern, a table-driven FSM, a std::variant FSM, and a probability-driven machine, with cross-check tests proving they agree.

Read page →
Chapter 11 · Command

Warehouse editor: Command + undo

Inventory operations encapsulated as command objects, with two undo strategies, an undo/redo stack, a FIFO command queue, and a std::function shortcut.

Read page →
Chapter 12 · Factories

Carrier integration: factories

An abstract factory produces a matching family of carrier products, and a factory method defers one creation step to a subclass, both removing concrete class names from the call site.

Read page →
Chapter 13 · Builder / Prototype

Freight manifest: build, clone, serialize

A fluent builder that validates once at build(), a prototype registry that clones named package templates into independent copies, and a text serialization round trip.

Read page →
Chapter 14 · Singleton

Audit log: singleton vs DI

A thread-safe Meyers singleton shown alongside its costs, then the same capability as a constructor-injected abstraction that a test can swap for a fake.

Read page →
Chapter 15 · Adapter / Facade / Bridge

Carrier integration: structural patterns

Adapter wraps a legacy rate API, a facade fronts the rating/labeling/tracking subsystems, a bridge crosses notification kinds with transports, and PImpl hides a renderer's implementation.

Read page →
Chapter 16 · Decorator / Proxy

Rate decorators and manifest proxies

A core rate source wrapped in stackable, order-sensitive decorators (logging, caching, surcharge), next to lazy-init and access-controlling proxies over a manifest store.

Read page →
Chapter 17 · Composite / Flyweight

Palletizing: composite + flyweight

A package tree where leaves and composites share one interface, a flyweight pool that shares SKU descriptors across many line items, and a Null Object that removes null checks.

Read page →
Chapter 18 · Observer / Mediator

Shipment tracking: observe and mediate

A tracker fans status changes out to interface and std::function observers with RAII subscriptions, and a mediator routes between warehouse, carrier, and customer stations that never know each other.

Read page →
Chapter 19 · Chain / Iterator

Approval chain and range traversal

A request travels a chain of approval handlers until one acts, and a bucketed manifest exposes a forward iterator that composes directly with views::filter and views::transform.

Read page →
Chapter 20 · Visitor / Memento / Interpreter

Shipping rules: visit, interpret, snapshot

The same six-node rule AST walked two ways (classic double-dispatch and std::variant/std::visit), interpreted to a match result, with a rule-set editor whose memento restores whole state.

Read page →
Chapter 21 · CRTP / Policies

Rate model: CRTP + policies

A CRTP base dispatches to derived rate models with no vtable, a reusable comparable mixin works across unrelated types, and a calculator is composed from interchangeable compile-time policies.

Read page →
Chapter 22 · Type erasure / PImpl

AnyRateQuoter and a PImpl ledger

A hand-written concept/model wrapper holds any quoter type by value with no shared base, and a PImpl ledger keeps its implementation behind a pointer so its header never leaks detail.

Read page →
Chapter 23 · Expression templates

Route metrics: lazy evaluation

An expression template that defers a weighted sum into a tree evaluated in one pass, proven against eager evaluation, plus a self-registering registry and a field-hook templated serializer.

Read page →
Chapter 24 · Resource pools

Connections: bounded and reused

A generic ResourcePool with an RAII lease that returns its resource on destruction, shown as a shipment-tracking connection pool, a label-rendering thread pool, a monitor object, and an active object that returns futures.

Read page →
Chapter 25 · Dispatch tables

Routing without a class hierarchy

An enum-indexed function-pointer table, an open unordered_map dispatch map, and a compile-time constexpr array, three ways to route a shipment message type to its handler without a full Strategy, State, or Command hierarchy.

Read page →
Chapter 26 · Anti-patterns

Patternitis, and backing out of it

A singleton registry, a factory-of-factories, and a god object, collapsed into one service that takes a settings value by injection. Tests prove the rewrite computes the same answer and is testable where the original was not.

Read page →
Chapter 27 · Seams

Pin behavior, then change it

Characterization tests pin a legacy SLA checker's current behavior, an object seam makes its clock substitutable so a boundary bug can be pinned and fixed under test, and a link seam breaks a free function's dependency on a grace-period policy.

Read page →
Chapter 28 · Dependency breaking

Making the untestable testable

A representative subset of Feathers' 24 techniques on inherited shipping code: extract interface and parameterize constructor, extract and override call, encapsulate global references, introduce instance delegator, and adapt parameter.

Read page →
Chapter 29 · Fowler and Feathers

Safety net first, then refactor

An inherited ETA estimator run through both methodologies in sequence: characterize and break its clock dependency (Feathers), then apply Extract Function, Replace Conditional with Polymorphism, and Introduce Parameter Object (Fowler), tests green at every step.

Read page →
Chapter 30 · Refactor or rewrite

Strangle the legacy engine

A legacy pricing engine with undocumented rules replaced by a bounded rewrite behind a stable interface. A strangler fig router shifts traffic customer by customer while a shared suite proves old and new agree before cutover.

Read page →
Chapter 31 · Final project

Five patterns, one system

A shipment dispatcher that composes Factory, Strategy, State, Command with undo, and Observer. The integration test proves the composition: a lifecycle run fires observer events in order, a command re-prices through the factory-built strategy, and undo restores the prior state.

Read page →
Chapter 32 · AI and LLM tools

Gate AI output on tests

A correct usage-tier Strategy beside an AI-plausible one carrying a single off-by-one at a billing-tier boundary. The identical behavior table passes on the correct implementation and catches the wrong one, showing why AI drafts are gated on tests, not trusted on read.

Read page →

Building every demo

Clone the repo and build each example from its directory with the pinned local toolchain (clang, CMake, Ninja, Conan 2.x; see the prerequisites chapter and scripts/check-prereqs.sh).

git clone https://github.com/patterncatalyst/cpp-design-patterns.git
cd cpp-design-patterns
./scripts/build.sh
./scripts/verify.sh cpp23

Every example is also standalone-buildable from its own directory with conan install and cmake --preset cpp23, without configuring the whole repo.