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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.