Skip to content

Software Design Patterns in C++

Glossary

131 terms from Software Design Patterns in C++, in plain words, each with the chapter that teaches it.

#

#pragma once
A line at the top of a header file that tells the compiler to include that file only once per build. It prevents 'defined twice' errors when several files include the same header.
= default
Tells the compiler to write the standard version of a special function for you, such as a constructor, destructor or `operator==`. For example, `virtual ~DiscountRule() = default;` gives a base class a virtual destructor, and a defaulted `operator==` compares an `Item` field by field.
= delete
Forbids a function from being used. Kettle & Crane's `Settings` singleton deletes its copy constructor so nobody can make a second copy.

A

Abstract class
A class with at least one pure virtual function, so you can't create an object of it directly. It exists to be inherited from, as `DiscountRule` and `Report` are.
Abstract factory
A pattern where one object has several make functions that create a family of parts that belong together, such as a carrier and a label printer for one shipping company. A simple factory is enough for most cases.
Adapter
A small class that wraps a library you can't edit and offers the shape your code expects, translating each call. `UpsCarrier` adapts UPS's cents-in-a-struct API to a `Carrier` that quotes dollars.
aggregate initialization
Filling in a plain struct's fields in order with braces, like `Product mug{"Speckled blue mug", 18, wholesale}`. It avoids writing a constructor.
Anti-pattern
A common answer to a design problem that looks reasonable but causes more trouble than it solves. Examples are the god object and magic numbers.
Architecture patterns (MVC, hexagonal, CQRS, microservices)
Patterns for organizing whole systems: MVC (Model-View-Controller), hexagonal architecture (ports and adapters), CQRS (separate reading and writing) and microservices (many small services). They apply the same design ideas as smaller patterns, but at the scale of an entire system.

B

Behavioral pattern
A pattern about how objects share work and decisions and talk to each other. Strategy, Observer and Command are behavioral patterns.
Builder
A pattern where an object collects the parts of a complicated object one call at a time, then makes and checks the finished thing in `build()`. `OrderBuilder` throws if you build an order with no items.

C

cache
Saved answers kept so the same question isn't asked twice. A caching proxy around a carrier asks UPS once per line count.
callable
Anything you can call like a function: a plain function, a lambda or a function object. `std::function` can hold any callable of a given shape.
Chain of responsibility
A pattern where a request passes along a line of handlers, and each handles it (for example by rejecting it) or passes it on. Kettle & Crane's order checks run this way, stopping at the first problem.
Characterization test
A test that records what existing code does today, right or wrong, so you can prove a redesign changes nothing. For example, pinning the totals 467.5, 42.6 and 31.25 before rebuilding `place_order`.
Class explosion
The growth of a new class for every mix of choices when inheritance is used. Two yes/no choices make 4 classes, three make 8.
Cohesion
How well the things inside one piece of code belong together. A function that only works out shipping has high cohesion, and you want high cohesion.
Command
A pattern that turns an action into an object that knows how to run itself and undo itself. Stored on an undo stack, such commands give the cart page an Undo button.
comparator
A function you hand to something like `std::sort` that says which of two items comes first. It is the rule that varies, so it is an example of a strategy.
Composite
A pattern that gives a single item and a group the same method, so the group asks each part and adds up. A gift bundle can hold items and other bundles, and one `price()` call prices any of them.
Composition
Building an object from smaller part objects it holds, a has-a relationship. A `Product` has a pricing part and a wrapping part rather than inheriting every mix.
Composition root
The one place, usually `main`, that builds the real parts and hands them to the code that needs them.
Concept
A named C++20 requirement on a template type, listing what functions a type must have. `DiscountLike` is a concept that checks for `applies` and `apply`.
const reference
A reference that lets callers read an object but not change it. `MemoryRepo::all()` returns one so callers can look at orders but not damage the vector.
Constructor injection
Passing an object its dependencies in its constructor, to keep for its whole life. `OrderLog` receives its repo, clock and notifier this way.
Copy-paste programming
The same code repeated in many places, so a fix is easily missed in one of them. The fix is one function called from every place.
Coupling
How much one piece of code depends on the details of another. You want loose coupling so changing one piece doesn't break another.
Creational pattern
A pattern about how objects get built. It moves the 'which class, with which settings?' decision into one place.
Crow
A C++ web framework in which `CROW_ROUTE` registers a lambda to handle requests for a web address. The framework looks up the route and calls the lambda when a browser asks for that address.

D

Decorator
A wrapper with the same interface as the object it wraps that does extra work and passes the call on. `LoggedCarrier` logs each quote without any carrier being edited.
Delegation
Handing a job to another object you hold. `Product::total` asks its pricing part and then its wrapping part.
Dependency
Anything code needs to do its job, such as a database, a notifier or the clock. The old `place_order` reached for all of them itself.
Dependency injection
Giving code its dependencies from outside instead of letting it find or make them. Tests can then pass in fakes, so they need no disk or clock.
Dependency inversion principle
The D in SOLID: high-level code shouldn't depend on low-level details, and both should depend on an interface. You pass the detail in, as `confirm_order` receives a `Notifier`.
Design pattern
A named, reusable solution to a common design problem. It is a shape for your code, not a library.
Designated initializers
C++20 syntax that names each field when filling in a struct, like `.carrier = "usps"`. It needs no builder class when all the parts are known at once.
DI container
A library that builds objects and their dependencies from a set of rules. C++ programs rarely need one because plain constructor calls in a composition root stay readable.
Duck typing
Judging an object by what it can do, not by its class: 'if it quacks like a duck, it's a duck'. C++ does it with templates checked at compile time, often with a concept.

E

Event
Something that happens, such as `"order_placed"`, announced by name so that listeners can react. The event bus's `emit` calls every listener registered under that name.
event bus
An object that keeps listeners under event names and calls them all when `emit` is called; it is the subject in the observer pattern. For example, an order service announces 'order_placed' and the bus calls every listener registered for it.
exception
A way to report an error by `throw`ing an object, which stops the function and is handled by a `catch` block around a `try`. `create_carrier("fedex")` throws `std::invalid_argument`.

F

Facade
One simple function or class in front of several parts, so only it knows the steps. `checkout` prices, quotes shipping and saves, so callers don't repeat the steps.
Factory method
A Gang of Four pattern where a parent class has a function that makes a part and each child class overrides it to choose which object to make. `SaverShipment` makes a USPS carrier.
Fake
A simple working stand-in used in tests, such as `MemoryRepo` or a notifier that keeps its messages in a vector.
Fixture
A helper that builds the object under test with fresh parts so no test sees another's data. `make_log` and `Parts` are fixtures.
Fragile base class
The problem that a change to a parent class quietly breaks its children. Adding sales tax to `Product::total` would also tax tax-free wholesale products.
Framework
Code that runs your program and calls your code at the right moments. A test runner or web framework is one, unlike a library that your code calls.
Function-local static
A `static` variable inside a function, built once the first time the function runs (thread-safe since C++11). It is the usual C++ form of a singleton.

G

g++
The GNU C++ compiler (a recent clang++ also works). `g++ -std=c++20 -Wall -Wextra file.cpp -o file` compiles with C++20 and extra warnings, and `./file` runs the result.
Gang of Four
The four authors of the book *Design Patterns* (1994), which named 23 patterns in three families: creational, structural and behavioral.
Generator
A function that hands back one item, then pauses until asked for the next. C++20 has none (`std::generator` arrives in C++23), so a lazy view is the nearest tool.
Global mutable state
A global variable that any code can change, like the old global `orders` vector. It makes behavior hard to predict and tests depend on each other.
Global state
A shared value any code can change. If one test sets the singleton's `free_shipping_at` to 50, later tests see 50 too.
gMock
GoogleTest's library for making mocks, which are stand-ins that record how they were called. Hand-written fakes are a simpler alternative for small tests.
God object
One class (or function) that does far too much, like a `Shop` with 40 functions for pricing, stock and email. Split it by reason to change.
Golden hammer
Using one favorite tool for every problem, such as a factory for everything. Choose the simplest tool that fits.
GoogleTest
A widely used C++ testing framework. Its `TEST_F` macro registers a test that gets a fresh fixture, and its `main` runs them.

H

Handler
One link in a chain of responsibility. It handles a request, for example by rejecting it, or passes it on.
Has-a / is-a
Two kinds of relationship between classes. Is-a is inheritance, as a wholesale product is a product, and has-a is composition, as a product has a pricing rule.
Hook
The step a template method leaves open for callers to supply. In the report example it is the row-format function.

I

Inheritance
A way for a child (derived) class to reuse its parent's (base class's) code and override its virtual functions. It models an is-a relationship, and deep trees of it cause class explosions.
Injected clock
A time function passed in as a dependency, a `std::function` that returns the time as text. Tests pass a fixed clock, and `main` passes the real `now_iso`.
Inline
A keyword that lets a function or variable be defined in a header and included by several `.cpp` files without a 'defined twice' error. An inline variable is one object shared by every file.
Interface
The set of functions code expects an object to have. C++ has no `interface` keyword, so you write one as an abstract class or as a template with a concept.
Interface segregation principle
The I in SOLID: code shouldn't depend on functions it doesn't use. Keep interfaces small, such as a separate `Quoter` and `Tracker`, so a quote-only carrier needs no fake `track`.
Inversion of control
The idea that a framework calls your code instead of your code calling it: 'don't call us, we'll call you'. Registering a route with `CROW_ROUTE` is an example.
ISO 8601
A standard text format for dates and times, such as `2026-10-23T16:00:00Z`. A clock function can return the time in this form.
Iterator
An object that steps through a collection one item at a time without showing how it is stored. Every range-for uses a container's `begin()` and `end()`, and `find` returns an iterator where `end()` means not found.

J

JSON
A common text format for data, with curly braces and `"key": value` pairs. The old `place_order` wrote `orders.json` by hand.

K

KISS
'Keep it simple': of two working designs, choose the one that is easier to read.

L

lambda
A small unnamed function written inline, which can capture variables like `[pct]`. Lambdas are usually how a strategy or listener is written in C++.
Library
Tools your code calls when it wants to, such as `std::sort`. Contrast a framework, which calls your code.
Liskov substitution principle
The L in SOLID: a child class must work anywhere its parent works. A `LockedCard` that throws in `top_up` breaks what a `GiftCard` promises.
Listener
A function that wants to hear about an event and is called when the event is emitted. `send_email` and `log_sale` listen for 'order_placed'.

M

Magic number
A number in code with no name, like `75` and `0.85` in the old `place_order`. Give it a named constant such as `FREE_SHIPPING_AT`.
Method chaining
Chained calls where each returns the same object, with `return *this`, so the next call follows straight on. `OrderBuilder().for_customer(ana).add(...).build()` is an example.
Middleware
Code every web request passes through, such as logging or login checks, each handler able to stop the request. It is the chain of responsibility pattern in web frameworks.
Mock
A test stand-in that also records how it was called so the test can check it. GoogleTest's gMock makes them.
mutable
A keyword that lets a data member change even inside a `const` method. The caching proxy marks its saved-answers map `mutable`.

O

Observer
A pattern where the code where something happens keeps a list of listeners and calls each one, without knowing what they do. Alex's packing slip becomes one new function and one `bus.on` line.
Open/closed principle
The O in SOLID: code should be open for extension but closed for modification, so you add behavior with new code instead of editing old code. A new `Fall15` rule is a new class plus one `push_back`.
Other patterns (not covered)
Six further Gang of Four patterns: Flyweight (share one object among many uses), Bridge (split a concept from its implementation), Mediator (one object handles how others talk), Memento (save state so it can be restored), Visitor (add an operation to classes without editing them) and Interpreter (a small language's grammar as classes).
Over-engineering
More structure than the problem needs, such as an abstract class, factory and registry for one discount.
override
A keyword on a child's function saying it replaces a parent's virtual function. The compiler checks the signature, so a misspelled name is an error.

P

Plugin
Code a framework finds and runs to add a feature without changing the framework, often a library loaded at startup. It is the open/closed principle applied to a whole tool.
Premature abstraction
Writing an interface, base class or factory before two or three real cases exist. A wrong guess about what will vary is hard to undo.
private
A class section that only the class's own functions can use, as `EventBus` keeps its `listeners_` map private. A trailing underscore marks such members.
Prototype
A pattern that makes new objects by copying a ready-made one and changing a little, like Bloom Café's weekly order. In C++ a struct copies with `=`, and a base pointer uses a `clone()` function.
Proxy
A same-interface wrapper that controls access, for example creating the real object only when needed, checking permissions or caching answers.
Publish/subscribe
Another name for the observer idea: the subject publishes events and listeners subscribe to them.
Pure virtual function
A virtual function written `= 0`, meaning every child class must provide it. A class that has one is abstract.

R

RAII
The C++ habit where an object's constructor acquires something and its destructor releases it, as `std::ifstream` opens and closes a file. It works like a hidden template method, and it is why a test's `Repo` is cleaned up automatically when its scope ends.
Registry
A table from names to functions or classes, like `CARRIERS` or the list of tests a runner holds. The framework looks things up there and calls them.
Repository
An object that stores and finds things for the rest of the code, so nothing else knows how they're stored. `Repo` is the interface and `MemoryRepo` an implementation.
route
In a web framework, a web address such as `/orders` tied to a function that handles requests for it. `CROW_ROUTE` registers the function.
Rule of three
Write code once, notice the repeat the second time, and extract the shared part the third time, when you know what varies.

S

Service locator
A global registry that code reaches into to find its dependencies, like `*REGISTRY.at("repo")`. It hides dependencies again, and tests must change a global.
Simple factory
One function that knows every class and returns the right object for a name. `create_carrier("ups")` looks up a maker lambda in the `CARRIERS` map.
Single responsibility principle
The S in SOLID: a piece of code should have one reason to change. `place_order` has many, so pricing and discounts are pulled out of it first.
Singleton
A class that allows only one instance and hands everyone that same instance. In C++ it is usually a function-local static, but changeable shared values become global state.
SKU
A product's stock code, like `ESP-5LB` or `MUG-BLUE`. It identifies each item in an order.
Slice
Copying a derived object into a base-class variable, which keeps only the base part. Holding wrappers by `unique_ptr` to the base avoids it.
SOLID
Five design principles named by their first letters: single responsibility, open/closed, Liskov substitution, interface segregation and dependency inversion.
Spaghetti code
Logic so tangled with ifs and globals that you can't follow one path through it.
State
A pattern for rules that depend on status. It is shown as a transitions table, or in the textbook form as one class per state whose methods return the next state or refuse.
State machine
Something that is always in exactly one of a fixed set of states, with rules for moving between them. An order can go from `shipped` to `delivered` but not to `cancelled`.
static_cast
An explicit C++ conversion from one type to another, such as turning the `size_t` count of items into an `int`.
std::function
A type that holds any callable with a given shape. `std::function<double(double)>` means anything you can call with a double that returns a double, which is how strategies and listeners are stored.
std::move
Hands over ownership of an object, such as passing a `unique_ptr` into a bundle, instead of copying it.
std::optional
A value that may or may not be present: it holds a message or is empty (`std::nullopt`), and counts as true in an `if` when it holds one. The order checks return one to report an error or nothing.
std::setprecision
Output formatting helpers from `<iomanip>`. `std::fixed` with `setprecision(2)` prints 467.5 as 467.50, and `setw` sets a value's width.
std::unique_ptr
A smart pointer that owns one object and deletes it automatically when the pointer goes away. Products, bundles and rule lists hold their parts this way.
std::unordered_map
A standard container that looks up values by key, used for tables such as `CARRIERS` and `TRANSITIONS`. `find` returns an iterator and `end()` means not found.
Strategy
One interchangeable way of doing a job, where all versions share a shape so the code using one doesn't care which it gets. In C++ it is usually a function or lambda, such as the discount functions chosen by `discount_for`.
String stream
`std::ostringstream` takes `<<` like `cout` but collects the text in a string, which `.str()` returns. The `money` helper uses one.
Structural pattern
A pattern about how objects fit together, such as connecting mismatched pieces or wrapping one object in another. Adapter and Decorator are structural.
Stub
A test stand-in that just returns a fixed answer, such as a clock that always says 4:00 p.m.
Subject
The object listeners subscribe to, which calls them when something happens. An event bus is an example.

T

Template
C++ code written once for any type that fits, such as a function using `template <typename T>`. Types are checked at compile time, which is how C++ does duck typing.
Template method
A pattern that fixes a job's steps in one place and leaves one step, the hook, for the caller to fill in. A report function takes a row-format function, or a base class has a pure virtual `format_row`. It is unrelated to C++ templates.
thread-safe
Safe to use when several threads run at once. C++11 guarantees a function-local static is built only once even then.
Transition
A move between states. The `TRANSITIONS` map lists which moves each order status may make.
Tree
A structure where items contain smaller items, down to single items. Nested gift bundles form a tree.

U

Undo stack
A vector of commands that have run, newest at the back. Undo reverses and removes the last one.
UTC
The standard world time, with no time zone. Timestamps in UTC are often shown with a trailing `Z`, as in `2026-10-23T16:00:00Z`.

V

vcpkg
A tool for adding C++ libraries, such as Crow, to a project.
View
A lazy window onto a container, from `<ranges>`, that produces one matching item at a time. It is the nearest C++20 tool to a generator.
Virtual destructor
A destructor marked `virtual` so that deleting a child through a base pointer runs the child's destructor. Every base class used through pointers needs one.
Virtual function
A member function marked `virtual` so a call through a base pointer or reference runs the child's version. It is how abstract classes, strategies and most class-based patterns work.

W

Wrapper
An object that holds another and stands in front of it. Adapters, decorators and proxies are all wrappers.

Y

YAGNI
'You aren't gonna need it': don't build for a need until it's real. Sam's 'in case we ever sell tea' factory fails this test.