Skip to content

How to study design patterns

Difficulty: Intermediate

Key concepts

  • design pattern
  • forces
  • consequences
  • creational structural behavioural
  • C++ idiom
  • architectural pattern
  • pattern recognition from requirements
  • What a design pattern is: a problem, the forces that make it hard, a solution shape, and its consequences.
  • The difference between the classic object-oriented patterns, C++ idioms, and architectural patterns, and why the difference matters.
  • How to recognise a pattern from requirement wording and code smells, and the simpler design to try first.
  • Which patterns come up most often in application design.
  • Why a good design usually uses zero to two patterns, and how to use a pattern in a design discussion.

A pattern is a named solution shape for a problem that keeps coming up, together with what it costs. It is not code you copy: it is a way of arranging responsibilities between a few classes or functions, which you then write for your own problem, in your own types.

Every pattern has four parts. Take Strategy as an example:

Part Question it answers Strategy
Problem What situation is this for? One job can be done in several ways, and the way must be chosen or changed
Forces What pulls the design in different directions? New ways keep being added; the code that needs the job done should not change each time; each way may need its own data
Solution Which roles, and who knows whom? The job goes behind an interface; the class that needs it holds one implementation
Consequences What does it cost, and what does it make easier or harder? One more interface and one class per way; the way can change at run time; each way is testable alone

The forces are the part most often skipped, and the most important. A pattern is right only when its forces are present. Strategy’s force is “new ways keep being added”. If there are three ways and there will always be three, that force is missing, and a switch is usually the better design, unless another of Strategy’s forces is present: a way that needs data of its own, or ways that must be tested alone.

The consequences are not footnotes. Every pattern adds types and indirection. A pattern is worth it when the consequences that help you (for example, adding a variant without editing tested code) matter more than the ones that cost you (more types to read, one more lifetime to manage).

People say “pattern” for three different things. Keeping them apart helps you know what to look for, and where.

Three kinds of reusable design: architectural patterns are often built from classic patterns, and in C++ the classic patterns lean on idioms for ownership and lifetime
Text description of the diagram

Three groups, connected by dashed “uses” arrows. Architectural patterns (how a whole application is split): dependency injection, Repository, Unit of Work, and layers. Classic object-oriented patterns, in three families: creational (how objects are made: Factory Method, Abstract Factory, Builder, Prototype, Singleton); structural (how objects are combined: Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy); and behavioural (how objects share work: Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, Visitor). C++ idioms (how C++ code is written): RAII, PImpl, type erasure, and policy-based design. Arrows labelled “is often built from” go from the architectural patterns to each of the three classic families. Arrows labelled “in C++ relies on” go from each classic family to the C++ idioms.

Diagram source (Mermaid)
flowchart TB
subgraph Arch["Architectural patterns: how a whole application is split"]
  AR["Dependency injection, Repository,<br/>Unit of Work, layers"]
end
subgraph Classic["Classic object-oriented patterns"]
  CR["Creational: how objects are made<br/>Factory Method, Abstract Factory,<br/>Builder, Prototype, Singleton"]
  ST["Structural: how objects are combined<br/>Adapter, Bridge, Composite,<br/>Decorator, Facade, Flyweight, Proxy"]
  BH["Behavioural: how objects share work<br/>Chain of Responsibility, Command,<br/>Interpreter, Iterator, Mediator, Memento,<br/>Observer, State, Strategy,<br/>Template Method, Visitor"]
end
subgraph Idioms["C++ idioms: how C++ code is written"]
  ID["RAII, PImpl, type erasure,<br/>policy-based design"]
end
AR -.->|"is often built from"| CR
AR -.->|"is often built from"| ST
AR -.->|"is often built from"| BH
CR -.->|"in C++ relies on"| ID
ST -.->|"in C++ relies on"| ID
BH -.->|"in C++ relies on"| ID

Classic object-oriented patterns. These are the 23 patterns catalogued in a well-known 1994 book by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, often called the “Gang of Four” (GoF) patterns. Each one arranges a few classes to solve a problem inside one part of a program. They are grouped by what they are about:

  • Creational patterns decide how objects are made, so that the code using an object does not have to know its concrete type or how to build it.
  • Structural patterns decide how objects are combined: wrapping one to change its interface or add behaviour, or treating a group as one.
  • Behavioural patterns decide how objects share work and talk to each other: who decides, who is told, and who does the job.

The patterns are not tied to one language, but they were written with languages like C++ and Smalltalk in mind. In modern C++, several have lighter forms: a Strategy can be a std::function, an Iterator is what every standard container already provides, and a Command can be a lambda in a queue. Some patterns exist partly to work around what a language lacks, and modern C++ lacks less.

Pattern names are also a shared vocabulary. Saying “the pricing is a Strategy” tells a reviewer, in three words, which class holds which object and what can change. That is only useful if the name is used for the problem it fits. Two patterns can have the same class diagram and still be different patterns: Strategy and State both delegate to an object behind an interface, but in Strategy the caller picks the object, and in State the object’s own stage in its lifecycle does. Learn each pattern by its problem, not by its diagram.

C++ idioms. These are about how C++ code is written, mostly ownership, lifetime, and compile-time structure: RAII ties a resource to an object’s lifetime; PImpl hides a class’s data members behind a pointer; type erasure gives value semantics to polymorphic objects (std::function is an example). An idiom does not solve a design problem by itself, but many patterns in C++ lean on one, because the pattern leaves ownership open: a Strategy must be owned by someone, and an Observer must not call a listener that has been destroyed.

Architectural patterns. These decide how a whole application is split into parts, and how those parts find each other: dependency injection passes each part what it needs instead of letting it create it; a Repository puts storage behind an interface the business rules own. They are bigger than one class, and they are often built from classic patterns.

This section covers all three, with the classic patterns first, each compared with the simpler designs that compete with it.

Recognise the problem before you name a pattern

Section titled “Recognise the problem before you name a pattern”

The most common mistake with patterns is starting from the pattern: “this is a good place for a Factory”. Start from the requirement instead, and let the pattern arrive only if the problem asks for it.

  1. Write the straightforward design first: one class, a function, a switch. Make it correct.
  2. Find the force. What is changing, or will change, that makes the straightforward design hard? “We add a new assignment rule every month” is a force. “We might need another rule some day” is not; it is a guess.
  3. Look for a pattern whose problem matches that force, not one whose diagram resembles your classes.
  4. Compare it with a simpler option: a parameter, a function, a lambda, an enum, a standard facility. The simpler option wins unless the pattern’s consequences are clearly worth its cost.
  5. Write down why. A one-line reason in the design (“Strategy, because the rule changes per weekday and new rules are planned”) lets a reviewer, or you in six months, check whether the force is still there.

The table maps phrases you will hear in requirements, or smells you will see in code, to the pattern to consider, and to the simpler design you should try first. Use it as a set of prompts, not as rules.

You hear or see Consider Try first
“Choose how to … per customer / per setting”; a switch on a “mode” repeated in several functions Strategy a switch or a function parameter, if the set of ways is fixed and small
“Every import (report, payment) must do these steps; only the format differs”; copied functions with the same shape Template Method one function that takes the varying step as a parameter
“Only allowed when the order is …”; “after it is shipped it cannot …”; if (status == …) in every member function State an enum class status and one switch per operation, while there are few states
“When X happens, A, B, and C must be told”; the list of who to tell keeps growing Observer direct calls, while the listeners are few and fixed
“Escalate to the next level if this one cannot”; “try each loader until one recognises the file” Chain of Responsibility a few ifs in one function, while the order is fixed
“Loop over the readings oldest first”; callers doing index arithmetic on your storage Iterator forward a standard container’s iterators, or use a view
“Rules written by people as text: member and not heavy or staff”; conditions that nest Interpreter a table of “all of / none of” rows, if the rules are flat
“Add another operation over the tree: print, check, export”; a dynamic_cast chain repeated in every operation Visitor, only if the kinds of node are stable a virtual function per operation, while there are only a few operations
“Undo must cover everything, including fields added later”; a history class reaching into another class’s getters and setters Memento keep a copy of a plain struct, if the state is already public
“Undo”, “redo”, “retry later”, “queue”, “log every action” Command a std::function in a container, if no undo is needed
“A sees B’s message unless A blocked B”; peer objects that each hold pointers to several of the others Mediator direct links, while there are only two or three fixed objects
“Create the right kind of X from the configuration (input, file type)” Factory Method, only if a base class must leave the choice of type to its derived classes a free function returning std::unique_ptr<Base> (a “simple factory”, not itself a classic pattern)
“Look and feel”, “platform”, “driver”: several kinds of object that must all come from one family Abstract Factory one factory function per kind, if mixing families is harmless
“Add logging (caching, retry, timing) around an existing service without changing it” Decorator a wrapper function, if only one call needs it
“A simple way to use this complicated library / subsystem” Facade a well-named class with a small interface, which is all a Facade is
“We must use the vendor’s API, but it does not match ours” Adapter none: if the mismatch is real, an Adapter is the simple option
“Every shape in every format”; class names that combine two words, such as SvgRectangle and TextRectangle Bridge one hierarchy, while only one of the two things actually varies
“A folder holds files and folders”; “an order holds items and bundles” Composite a plain tree of values, if all nodes behave the same
“Millions of characters / tiles / trees”, most of them the same; memory runs out Flyweight plain values, if the objects are few or the repeated part is small
“Load it only when it is opened”; “only some users may see it”; the real object is slow to create, or somewhere else Proxy load everything up front, if it is small
“Many optional settings; check them all before creating the object” Builder an aggregate with default member values and a validating factory function
“Save as preset”, “duplicate”, “copy and paste”: copy an object known only through a base class Prototype plain value types (a std::variant), if you own every kind
“There must be only one” Singleton (usually not) create one instance in main and pass it to whoever needs it

The last row is a warning, not a recommendation. “Only one” is almost always true of one program, not a law of the type, and a Singleton turns it into hidden global state. See dependency injection for the usual alternative.

In our judgement, from the kind of application design this site teaches (booking systems, stores, games, tools, services), the patterns fall into three groups by how often they earn their place:

  • Often: Strategy, Observer, and State. Many applications have a rule that varies, an event that several parts care about, or an object whose allowed operations depend on its status.
  • Sometimes: Factory Method (or a simple factory function), Template Method, Decorator, Facade, Command, Adapter, Composite, Proxy, and Mediator.
  • Rarely: Builder (C++ aggregates, and since C++20 designated initializers, cover most cases), Abstract Factory, Bridge, Chain of Responsibility, Visitor, Flyweight, Interpreter, Memento, Prototype, and Singleton (which is usually a mistake).
  • Already done for you: Iterator. Every standard container provides iterators, so you write one only for a container of your own.

This is a rough guide to where to spend study time first, not a ranking of importance. Each pattern page says where its pattern shows up and where it does not.

A good design for one problem, such as a parking lot, a library, or a ticket desk, usually uses zero to two patterns. That is not a quota. It follows from the forces: most requirements are stable, and only one or two parts of a system are expected to vary in a way that needs a seam.

Signs that a design has too many:

  • A pattern was chosen before the requirement that needs it was found.
  • Interfaces with one implementation, created “so we can add more later”.
  • A reader must open five files to follow one simple request.
  • Names that describe the pattern and not the domain: PricingStrategyFactoryManager instead of Pricing.

When patterns hurt shows a small program built with five unneeded patterns, what that costs in testing, concurrency, and reasoning, and how to simplify it.

Every pattern page in this section follows the same order, so you can compare them:

  1. The problem, with numbered requirements, before the pattern is named, and the wording that suggests it.
  2. The straightforward solution, compiled and tested, and where it breaks.
  3. Sorting the data and functions: which class should own which data member and which function, and why.
  4. The pattern: its intent in one sentence, its roles mapped to C++ types, a class outline, and a diagram.
  5. The C++ implementation, with ownership and lifetime spelled out, a step-by-step trace, and the program’s real output and tests.
  6. When to use it and when not to, its costs, the alternatives (including no pattern), and common misuse.
  7. What happens when a requirement changes, an exercise, and how the pattern differs from its neighbours.

Every example program in the main text is compiled with GCC and Clang, with warnings treated as errors, and its tests are run. Exercise answers that are outlines say so.

Pages are added to this section as they are written. Available now:

Pattern Family Problem it solves
Strategy behavioural one job, several ways to do it, chosen or changed while running
Template Method behavioural the same steps in the same order, with a few steps that differ
State behavioural what an object may do, and the data it needs, depend on its stage in a lifecycle
Command behavioural operations that must be kept after they run: undo, history, groups, queues
Observer behavioural several objects must react to a change, and the set of them changes while running
Chain of Responsibility behavioural several handlers might deal with a request; the first that can should, and which ones exist, in what order, varies by configuration
Iterator behavioural your own collection stores elements in a different order or shape from the one callers walk them in
Interpreter behavioural sentences of a small language (rules, filters, queries) must be checked and evaluated while the program runs
Memento behavioural an object’s state must be saved and restored later, without exposing its internals to the code that keeps the copies
Visitor behavioural new operations keep being added over a stable set of classes, and each must handle every class
Mediator behavioural several peers must coordinate, and the rules involve more than one of them at once
Factory Method creational the same “which class do I create?” choice is made in several places, or must grow from outside
Abstract Factory creational several kinds of object must all come from one family, chosen once
Builder creational many optional parts, collected step by step, with rules about how they combine
Prototype creational objects held through a base class, often set up while running, must be copied without naming their classes
Singleton creational almost never: a type that truly cannot have a second instance; usually, create one in main and pass it in
Adapter structural an existing class does the right job with the wrong interface, often at a system boundary
Bridge structural a design varies in two independent ways, and one class per combination would multiply the classes
Composite structural a tree of parts and wholes, where most code should treat one item and a group the same way
Decorator structural optional steps (compress, encrypt, log, retry) must be added around an object and combined in any order
Facade structural several classes must be used together in an order, and most callers need the same few jobs from them
Flyweight structural very many objects repeat a large, unchanging part of their state, and memory matters
Proxy structural a stand-in must control access to a real object: create it late, check permission, or reach it elsewhere

Comparison pages help you choose between patterns that look alike:

The architecture section covers layers, ports and adapters, composition roots, Repository, and Unit of Work in depth; it starts with layered architecture, and the later pages are planned.

Exercise: Classify six techniques

For each technique, say whether it is a classic object-oriented pattern (and which family), a C++ idiom, or an architectural pattern. “None of these” is an allowed answer if you can say why.

  1. A std::lock_guard that unlocks a mutex when it goes out of scope.
  2. A Thermostat that keeps a list of displays and tells each one when the temperature changes.
  3. An OrderRepository interface that the order rules use to store orders, implemented once for a database and once in memory for tests.
  4. A class whose header holds only a std::unique_ptr<Impl>, so that changing its data members does not recompile its users.
  5. A ReportBuilder that collects many optional settings and checks them before creating a Report.
  6. Passing a comparison function to std::sort.
Show the explained answer
  1. C++ idiom: RAII. The lock’s lifetime is the scope; this is about resource ownership, not about dividing responsibilities.
  2. Classic, behavioural: Observer. The thermostat tells a changing list of listeners about an event. In C++, it also needs an ownership decision: what happens when a display is destroyed first?
  3. Architectural: Repository (with dependency inversion). It decides how the application’s rules are separated from storage.
  4. C++ idiom: PImpl. It is about compile-time dependencies and hiding data members, not about behaviour.
  5. Classic, creational: Builder, in its most common modern form: an object that collects options step by step and validates them before creating the result. (The original Builder also lets the same steps produce different representations; this one does not need that.) Before using it, check whether an aggregate with default member values and one validating function would do.
  6. The idea of Strategy, as a standard facility. The sort’s steps are fixed and the comparison varies, which is exactly Strategy’s problem. But in a design discussion you would just say “it takes a comparator”: a standard facility, or a plain function parameter, is the lightweight form, and naming a pattern adds nothing.

Exercise: Requirement first

A library system has these requirements. For each, name the pattern you would consider, the simpler design you would try first, and which you would choose today.

  1. “Members can borrow up to 5 books; staff up to 20.”
  2. “When a reserved book is returned, the member who reserved it is emailed, the front desk screen is updated, and, from next year, a text message is sent.”
  3. “A loan is active, overdue, or returned. An overdue loan cannot be renewed; a returned loan cannot be returned again.”
Show the explained answer
  1. Consider Strategy; choose data. The two kinds of borrower differ only in a number. A max_loans value on the member type (or a small lookup from member kind to limit) is enough. A Strategy would add an interface to hold one integer.
  2. Consider Observer; probably choose it. The list of who must be told is already growing (“from next year…”), and the code that records the return should not change each time it grows. With only two fixed listeners, two direct calls would be simpler; the planned third one is the force. In C++, the lightest form is a list of callbacks, std::vector<std::function<void(const Book&)>>; a listener interface is worth it when listeners need more than one function or must unsubscribe.
  3. Consider State; choose an enum class today. Three states and two rules fit comfortably in one class: an enum class LoanStatus, and renew and give_back that check it and throw a logic_error. Move to State if each status gains several different behaviours.

The design uses one pattern, which is typical.

  • A pattern is a problem, its forces, a solution shape, and its consequences. Use it only when the forces are present.
  • Classic patterns arrange a few classes (creational, structural, behavioural); C++ idioms handle ownership, lifetime, and compilation; architectural patterns split a whole application.
  • Start from the requirement, write the straightforward design, find the force, and only then look for a pattern. Always compare it with a simpler option.
  • In our judgement, Strategy, Observer, and State earn their place most often; Singleton rarely does.
  • A good design usually needs zero to two patterns, each with a one-line reason.