Chapters

The whole book, in order.

Twelve parts, read in order the first time through. Each chapter also stands on its own for a reader jumping in to solve one problem. Pick a part, or start at the top.

Part 0 Orientation

The toolchain (clang, CMake, Conan, GoogleTest), how to read the book, and the codetabs convention that carries C++20 and C++23 side by side through every chapter.

  1. Prerequisites and the toolchainThe clang, gcc, CMake, Ninja, and Conan toolchain on Fedora 44, the cpp23/cpp20 presets, the codetabs convention, and how every example is built, run, and tested.

Part 1 Recognizing Design

Patterns as decisions under forces, not recipes to apply by reflex, and the shared vocabulary a team (and an AI pairing partner) needs to name what it sees.

  1. Patterns as decisions under forcesWhy a design pattern is a named response to a recurring set of trade-offs rather than a recipe to apply from memory, and the five steps every pattern chapter follows.
  2. Naming the pattern: shared vocabulary for teams and AI assistantsHow a pattern's name turns a paragraph of trade-off reasoning into a word a reviewer can act on, and why that same compression is now the sharpest tool you have for prompting and reviewing an AI pairing partner.

Part 2 Principles (SOLID, Martin)

The five SOLID principles in modern C++ terms: SRP/OCP/LSP first, then ISP/DIP and dependency injection without a framework.

  1. SOLID I: single responsibility, open/closed, Liskov substitutionSplitting a billing engine along the lines of what changes: one responsibility per type under the Single Responsibility Principle, a rule abstraction that is open to new tax and discount behavior without edits under the Open/Closed Principle, and a refined discount rule that honors its parent's contract under Liskov Substitution.
  2. SOLID II: interface segregation, dependency inversion, and DI without a frameworkSegregating a fat interface into focused role interfaces, inverting the dependency between a high-level policy and a low-level implementation, and composing the resulting object graph by hand, in idiomatic C++ with no DI container.

Part 3 The C++ Substrate

RAII and deterministic lifetimes, value semantics and smart-pointer ownership, and proving a design works with GoogleTest before the patterns chapters begin.

  1. RAII and deterministic lifetimesTying a resource's lifetime to an object's lifetime instead of a bool flag a caller has to remember: acquire in the constructor, release in the destructor, exception-safe by construction, taught against a warehouse dock-bay lease and a general-purpose scope-exit utility.
  2. Value semantics, ownership, and smart pointersFour ownership shapes in a warehouse dispatch system: a value type that follows the Rule of Zero, sole ownership transferred by move with unique_ptr, a resource-owning Rule of Five type shared by shared_ptr, and a parent/child object graph where weak_ptr breaks a reference cycle.
  3. Proving it works: testing with GoogleTestThe shared testing foundation every pattern in this book is verified against: GoogleTest fixtures, parameterized and typed tests, GoogleMock interaction tests, and death tests, taught against a freight carrier's quote intake component.

Part 4 Selecting and Varying Behavior

Strategy, Template Method with non-virtual interface, State and finite-state machines (including probabilistic ones), and Command with undo and command queues.

  1. StrategyThree idiomatic C++ ways to select a varying algorithm at runtime or compile time, taught against a real shipping-rate example: an abstract interface behind a unique_ptr, a std::function value, and a compile-time policy constrained by a concept.
  2. Template Method and the non-virtual interfaceA fixed algorithm skeleton that calls private virtual hooks for the steps that vary, taught against an order export pipeline that produces a CSV manifest, newline-delimited JSON, and a fixed-width EDI feed from the same five-step sequence, with the non-virtual interface idiom protecting the sequence itself from every subclass.
  3. State and finite state machinesA shipment's lifecycle modeled four ways: the GoF State pattern with one type per status, a data-driven enum-plus-transition-table machine, a std::variant dispatched with std::visit, and a probability-driven machine whose weighted transitions are made reproducible by injecting a seeded random engine.
  4. Command, undo, and command queuesTurning a warehouse editor's operations into Command objects with their own execute and undo, an undo/redo stack that steps back and forward through a session, a FIFO queue that defers and batches execution, and the std::function shortcut for a queued action with nothing to undo.

Part 5 Creating Objects Under Control

Factory Method and Abstract Factory, Builder and Prototype (with serialization), and Singleton alongside the dependency-injection alternative.

  1. Factory Method and Abstract FactoryTwo idiomatic ways to keep object creation out of client code, taught against a carrier integration domain: an Abstract Factory that hands out a matching family of label formatter, rate quoter, and tracking client per carrier, and a Factory Method that lets an onboarding environment decide which integration test suite runs inside a fixed sequence.
  2. Builder, Prototype, and serializationA fluent builder that assembles a multi-field shipment manifest and validates it only once, at build(), a small named registry of package prototypes that clone into fresh independent copies, and a plain-text serialization format that round-trips a manifest back to an equal value, taught against a freight dispatch domain.
  3. Singleton, and the dependency-injection alternativeThe thread-safe Meyers singleton, the real costs it hides behind a convenient accessor, and the constructor-injected abstraction that gives the same capability without the global state, wired by a framework-free composition root.

Part 6 Composing and Adapting Structure

Adapter, Facade, and Bridge (with PImpl), Decorator and Proxy, and Composite and Flyweight alongside the Null Object idiom.

  1. Adapter, Facade, Bridge, and PImplFour structural techniques taught in one cohesive shipping subsystem: an Adapter that wraps a legacy carrier rate API behind a domain interface, a Facade that fronts rating, labeling, and tracking with one call, a Bridge that lets a notification's kind and its delivery transport vary independently, and the PImpl idiom hiding a label renderer's formatting behind a compilation firewall.
  2. Decorator and ProxyTwo structural patterns that wrap an object behind its own interface, taught against a carrier rate pipeline and a manifest archive: Decorator stacks layers that each add one responsibility in an order that changes the result, and Proxy stands a single surrogate in front of an expensive or access-controlled subject without adding any new capability.
  3. Composite, Flyweight, and Null ObjectComposite treats one item and a whole pallet the same, Flyweight shares a few SKU descriptors across many line items, and Null Object removes the null checks from a weight-limit walk.

Part 7 Coordinating and Traversing

Observer and Mediator, Chain of Responsibility and Iterator with ranges, and Visitor, Memento, and Interpreter.

  1. Observer and MediatorTwo coordination patterns for a many-party system, taught against a shipment tracker and a warehouse dispatch board: Observer fans a status change out to independently subscribed listeners, from a classic interface down to a lightweight std::function callback, and Mediator centralizes a many-to-many conversation behind one hub so a warehouse, a carrier, and a notification service never reference each other directly.
  2. Chain of Responsibility and IteratorTwo patterns for coordinating a collection of objects rather than one: Chain of Responsibility routes a request through a sequence of handlers until one of them acts, and Iterator provides sequential access to an aggregate without exposing its internal structure, taught with a shipment-approval chain and a zone-bucketed package manifest, including the C++20 ranges form of traversal.
  3. Visitor, Memento, and InterpreterThree patterns for a fixed shipping-filter rule tree: Visitor adds operations over the tree two idiomatic ways, the classic GoF double dispatch and a std::variant plus std::visit, Interpreter walks the same tree to evaluate a small filter grammar, and Memento snapshots and restores a whole draft rule set in one call.

Part 8 Idiomatic C++ Expressions

CRTP and policy-based design, type erasure alongside PImpl, and expression templates, serialization, and prototype registries.

  1. CRTP and policy-based designTwo idiomatic C++ expressions of static polymorphism on the shipping-rate domain: a CRTP base that resolves a derived type's method at compile time, a reusable CRTP mixin across unrelated types, and a host class composed from compile-time policies with no runtime dispatch.
  2. Type erasure and PImplType erasure as a value-semantic wrapper around a hand-written concept/model pair that holds unrelated quoters with no shared base class, and PImpl as a compilation firewall: correct special members, ABI stability, and when each idiom earns its cost.
  3. Expression templates and generic idiomsExpression templates that build a compile-time expression tree so a+b+c evaluates in one pass with no intermediate objects, plus two supporting idioms from the same freight-route domain: a self-registering Prototype registry and a single describe hook that drives both serialize() and deserialize().

Part 9 Patterns in the Wild

Resource pools (connection, thread, object, monitor, and active object), shortcut patterns such as function-pointer tables and dispatch maps, and anti-patterns to recognize and avoid.

  1. Resource poolsA generic, bounded resource pool with an RAII lease handle, taught against a shipment-tracking connection pool, plus three sibling concurrency shapes from the same domain: a thread pool rendering shipping labels, a monitor object, and an active object.
  2. Shortcut patterns: dispatch tables and mapsThree lightweight alternatives to a full Strategy, State, or Command class hierarchy, taught against a shipment-tracking ingestion service: an enum-indexed function-pointer table (the classic jump table), a std::unordered_map dispatch map for an open, runtime-extensible set, and a constexpr std::array table checked complete at compile time.
  3. Anti-patterns and pattern misuseRecognizing patternitis in a shipping codebase: a singleton configuration registry holding global mutable state, a factory-of-factories wrapped around interfaces with one implementation each, a god object that validates, logs, and formats, and a leaky abstraction that exposes its own call order. The simplified rewrite collapses six types into one class and two plain values, computes the same answer, and is testable where the original was not.

Part 10 Changing Inherited Code (Modernized Feathers)

Seams and the test safety net, the 24 dependency-breaking techniques updated for C++20/23, Fowler contrasted and combined with Feathers, and when to refactor versus rewrite.

  1. Seams and the test safety netGetting inherited C++ under test before changing it: characterization tests pin a shipment-SLA checker that reads the wall clock, an object seam makes the clock substitutable so the deadline boundary can be pinned and corrected, and a link seam replaces a free function's grace-period policy at link time.
  2. The 24 dependency-breaking techniques for C++20/23Michael Feathers' 24 dependency-breaking techniques mapped to modern C++, then applied to inherited shipping code: a mail dependency behind an interface and a defaulted constructor parameter, a clock read isolated into an overridable call, a mutable global behind an accessor, a static lookup behind an instance delegator, and a file-parsing parameter adapted down to the two values a caller reads.
  3. Fowler and Feathers: contrasted and combinedMartin Fowler's Refactoring and Michael Feathers' Working Effectively with Legacy Code compared on an inherited shipping ETA estimator, then run in sequence: Feathers first to build a safety net, Fowler next to apply named refactorings, with every test green at each step.
  4. Refactor or rewriteChoosing between incremental refactoring and a bounded rewrite, taught against a legacy freight-pricing engine with an undocumented zone-rate matrix, two undocumented customer overrides and an unexplained rounding rule. A strangler fig router replaces it behind a stable PricingEngine interface, customer by customer, after a shared characterization table shows the new engine agrees with the old.

Part 11 Putting It Together

A final project that composes several patterns from the book, and a look at working with AI and LLM tools as a pattern-literate collaborator rather than a code vending machine.

  1. Final project: composing patterns into a systemA shipment dispatch console that composes Strategy, Factory, State, Command and Observer into one system, taught at the seams where the patterns meet rather than re-teaching any one of them.
  2. Working with AI and LLM toolsUsing an LLM as a pattern-literate collaborator: name the forces and the candidate pattern, recognize over-patterning, hallucinated APIs and outdated C++, and gate every draft on behavior tests plus an idiomatic review. A usage-tier Strategy pairs a correct classifier with a plausible one carrying a single off-by-one at a billing boundary, caught by the same table run against both.

Part 12 Appendices

A build and toolchain reference, a GoogleTest reference, a gMock mocking reference, an xUnit test-patterns guide, a pattern-to-force quick reference that maps every pattern, principle, and idiom in the book to the forces it answers, a code-first review of the wider programming-principle vocabulary beyond SOLID, and a C++-specific review of large-scale physical design: components, levelization, and insulation.

  1. Build and toolchain referenceA one-stop reference for building and testing every example: the pinned toolchain, the two CMake presets, how Conan supplies GoogleTest, the per-example and whole-repo build paths, and the hook for revisiting C++26 once its headline features settle.
  2. Testing with GoogleTestA reference for the GoogleTest macros, assertions, fixtures, and parameterized/typed/death tests the examples use, and how they run through CTest.
  3. Mocking with gMockA reference for gMock: defining mocks with MOCK_METHOD, setting expectations with EXPECT_CALL, matchers, cardinalities, actions, sequences, and the nice/strict spectrum, all on shipping collaborators.
  4. xUnit test patternsGerard Meszaros's xUnit test patterns, the four-phase test, the test-double taxonomy, fixture strategies, and the common test smells, mapped onto GoogleTest and gMock.
  5. Pattern-to-force quick referenceA completeness ledger: every GoF pattern, SOLID principle, and C++ idiom mapped to the force that justifies reaching for it, each linked to where it is built. Scan it to find the tool for a force in front of you, or to confirm the catalogue is complete.
  6. Programming principles, reviewed in codeA code-first review of the wider programming-principle vocabulary beyond SOLID: the names an engineer is expected to know, each grounded in a before-and-after shipping-domain C++ snippet and a note on where the principle costs something.
  7. Large-scale C++: physical design, reviewed in codeA code-first review of John Lakos's physical-design discipline for C++, the component, levelization, and insulation, on the shipping domain.