Pattern, or a simple function, value type, or standard facility?
What you will learn on this page
Section titled “What you will learn on this page”- Six questions to ask before you write a pattern’s classes.
- How a lambda passed to a standard algorithm replaces a Strategy hierarchy, and a range-for loop replaces a hand-written Iterator.
- How a struct with defaults and designated initializers replaces a Builder for plain settings.
- How an
enum classand a function that returnsstd::optionalreplace a State hierarchy for a small, data-free life cycle. - How a
std::variantof values replaces a class hierarchy for a closed set of kinds. - How returning a value replaces an Observer that only ever has one listener.
- For each one, the signs that the pattern would be the better choice.
Why a pattern can be more than the problem needs
Section titled “Why a pattern can be more than the problem needs”A design pattern is a named answer to a recurring problem, described with classes and their relationships. Some of those problems are about something C++ can already say in one line:
- “pass a piece of behaviour to this function” is a lambda;
- “this value is one of these few kinds” is an
enum classor astd::variant; - “visit each element that matches” is a loop or an algorithm;
- “build a value with some settings left at their defaults” is a struct with default member initializers;
- “maybe there is no result” is
std::optional; - “tell the caller what happened” is a return value.
When the simple form says everything the problem needs, the pattern’s classes are extra code to read, test, and keep in step; the When patterns hurt page shows where that leads when it happens across a whole program. The question is never “is this a pattern?” but “what does the pattern give this problem that the simple form does not?” Sometimes the answer is “a lot”, and the pattern wins. This page shows both.
Six questions to ask first
Section titled “Six questions to ask first”Before writing a pattern’s classes, ask:
| Question | If yes, start with |
|---|---|
| 1. Is the part that varies one call, chosen by the caller? | a lambda or function parameter |
| 2. Is the job a loop over a collection? | a range-for loop or a standard algorithm |
| 3. Is the object plain settings, each with a sensible default? | a struct with default member initializers |
| 4. Is it a life cycle whose stages have no data of their own? | an enum class and a transition function |
| 5. Is the set of kinds fixed, and each kind data? | a std::variant of small structs |
| 6. Is only the caller interested in the result, right now? | a return value |
If you answer “no”, or “yes, but…”, read the “when the pattern earns its place” part of the matching section below. A “no” usually means the problem has the force that the pattern was made for.
The example: one shop, six pairs
Section titled “The example: one shop, six pairs”A small online shop sorts products, lists what is in stock, searches,
tracks an order, charges for delivery, and prints a receipt. Each of
these jobs is written twice in the example: once with a pattern (in
namespace pattern) and once in the simple form. The tests check that
each pair gives the same results.
Every pair works on this struct:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One product in the shop. A plain value: four public members and no// rules to protect, so it is a struct with no constructor. A caller makes// one with a brace list in member order, {"kettle", 2999, 4, 3}, and any// member left out keeps the default written after its `=`. Money is in// whole cents (2999 is 29.99), so no rounding error can creep in.struct Product { std::string name; int price_cents = 0; int rating = 0; // 1 to 5 stars int stock = 0; // units on the shelf
// `= default` asks the compiler to write ==: two products are equal // when every member is equal. main and the tests use it, through the // vector ==, to check that two sorted lists match product by product. bool operator==(const Product&) const = default;};
// True when at least one unit is on the shelf. A free function rather than// a member, because it needs only public data. `inline` lets the body sit// in a header that several .cpp files include without a link error.inline bool in_stock(const Product& product) { return product.stock > 0; }
// The products' names, joined with ", ", in the order given.std::string names(const std::vector<Product>& products);Product is a plain value: public data members, a defaulted ==,
no invariant that a constructor must protect. in_stock is a free
function, because it needs only the product’s public data.
1. Strategy, or a comparison passed to the algorithm
Section titled “1. Strategy, or a comparison passed to the algorithm”The pattern form. The shop wants products sorted in different orders. A Strategy gives the order an interface, and one class per order:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A Strategy for ordering products: one interface, one class per order.// The interface has a single question, `before(a, b)`: "should the first// product come before the second?". A sort needs only that one answer.class ProductOrder {public: // Virtual, so that deleting a derived order through a pointer to // ProductOrder (as a std::unique_ptr<ProductOrder> does) runs the // derived class's destructor too. virtual ~ProductOrder() = default; // `= 0` makes this pure virtual: ProductOrder has no answer of its own, // and every concrete order must supply one. It must be a strict "less // than": before(a, a) is false, as a sort requires. virtual bool before(const Product& a, const Product& b) const = 0;};
// Lower price first. `final` says no class may derive from this one.class CheapestFirst final : public ProductOrder {public: bool before(const Product& a, const Product& b) const override;};
// Higher rating first; between two products with the same rating, the// cheaper one first.class BestRatedThenCheapest final : public ProductOrder {public: bool before(const Product& a, const Product& b) const override;};
// Sorts in the given order; products that tie keep their relative order.// `products` is changed in place (a non-const reference); `order` is only// read, so any ProductOrder, including a temporary such as// BestRatedThenCheapest{}, can be passed.void sort_products(std::vector<Product>& products, const ProductOrder& order);Look at how sort_products works:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
void sort_products(std::vector<Product>& products, const ProductOrder& order) { // The algorithm already takes the varying step; the class only wraps it. // std::stable_sort reorders the whole vector, from begin() to end(), // asking the comparison "does the first product go before the // second?" as often as it needs. // "Stable" means two products the order calls equal (neither goes // before the other) keep the order they had. The lambda captures // `order` by reference ([&order]), so no copy of the strategy is // made, and simply forwards each question to `order.before(a, b)`. std::stable_sort(products.begin(), products.end(), [&order](const Product& a, const Product& b) { return order.before(a, b); });}It turns the strategy back into a lambda, because std::stable_sort
already takes the varying step as a parameter. The comparison
argument of a standard sort is the Strategy pattern, built into the
library.
The simple form. Pass the comparison directly:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Copy the catalogue first (catalogue is const, and sorting changes the// order of its elements), then sort the copy.std::vector<Product> by_price = catalogue;// The ranges version of stable_sort takes the whole vector, not a// begin/end pair. Its two extra arguments are:// std::ranges::less{} - the comparison: "is the left value smaller?"// &Product::price_cents - a projection: a pointer to a member, which// tells the sort to compare each product's// price_cents rather than the products.// Together: cheapest first. Equal prices would keep their old order.std::ranges::stable_sort(by_price, std::ranges::less{}, &Product::price_cents);
std::vector<Product> by_rating = catalogue;// A rule with a tie-break needs both products, so it is a lambda that// answers "does `a` go before `b`?". [] captures nothing: it needs only// its two parameters.std::ranges::stable_sort(by_rating, [](const Product& a, const Product& b) { if (a.rating != b.rating) { return a.rating > b.rating; // best rated first } return a.price_cents < b.price_cents; // then cheapest});How this code works: the two standard sorts
Both calls sort a copy of the catalogue, so the catalogue keeps its own order for the later sections.
- By price.
std::ranges::stable_sort(by_price, std::ranges::less{}, &Product::price_cents)reads as “sortby_price, comparing with less-than, and compare each product’sprice_cents”. The projection&Product::price_centsis applied to both products beforelessis asked, so the sort never compares whole products. - By rating, then price. The lambda answers “does
ago beforeb?”. If the ratings differ, the higher rating goes first, so it returnsa.rating > b.rating. Only when the ratings are equal does it look at the prices, and the cheaper one goes first.
With the five products in main:
| Product | Price | Rating | Place by price | Place by rating, then price |
|---|---|---|---|---|
| kettle | 29.99 | 4 | 4 | 4 |
| desk lamp | 19.99 | 5 | 3 | 2 |
| notebook | 4.99 | 4 | 2 | 3 |
| office chair | 89.99 | 3 | 5 | 5 |
| lamp bulb | 2.99 | 5 | 1 | 1 |
The lamp bulb and the desk lamp both have 5 stars, so the tie-break puts the cheaper lamp bulb first; the same happens to the notebook and the kettle at 4 stars. These are the two lines the program prints first, under “Running the example” below.
The first call uses a projection: &Product::price_cents tells
std::ranges::stable_sort to compare the prices, with
std::ranges::less. The second passes a lambda for a rule with a
tie-break. Neither needs a name, a header, or a class.
Why the simple form fits here. Each order is one call,
before(a, b), chosen at the call site and used once. The lambda sits
next to the call, so a reader sees the rule where it is used. There is
no object to own and no lifetime to think about.
When the pattern earns its place.
- The order is stored and chosen later, for example from a menu.
That is already a Strategy, held as a
std::functionor a table of named comparisons. A class interface adds something only when the next two points apply. - Each order is a role with several related functions: a name to show, a comparison, a description, perhaps a key for caching. Several functions that must stay consistent belong in one class, and that is a Strategy.
- The order is provided by code you do not compile, such as a plug-in, which needs a stable interface.
2. Iterator, or a range-for loop and an algorithm
Section titled “2. Iterator, or a range-for loop and an algorithm”The pattern form. An iterator class with has_next and next,
in the style of some other languages, walks the products in stock:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// An Iterator written the way some other languages do it: it walks the// products that are in stock and skips the rest.// The idea: index_ always points at the next in-stock product to hand// out, or at the end of the vector when there are none left. Every step// that moves index_ forward then skips past out-of-stock products, so// has_next() only has to compare index_ with the size.class InStockIterator {public: // Borrows products, which must outlive the iterator and not change while it is used. // `explicit` stops a vector from silently turning into an iterator. // The constructor already skips any out-of-stock products at the front. explicit InStockIterator(const std::vector<Product>& products);
// True while there is another in-stock product to hand out. bool has_next() const; // Hands out the current in-stock product, then moves past it. The // reference points into the borrowed vector, not into the iterator. const Product& next(); // throws std::out_of_range when has_next() is false
private: // Moves index_ forward until it reaches an in-stock product or the end. void skip_out_of_stock();
// A pointer, not a reference member, so the class stays assignable; // it is only borrowed, so the iterator never deletes it. const std::vector<Product>* products_; // never null std::size_t index_ = 0; // position of the next product to look at};
// The names of the in-stock products, joined with ", ", and how many// there are, both written with the iterator above.std::string names_in_stock(const std::vector<Product>& products);std::size_t count_in_stock(const std::vector<Product>& products);Every use is a hand-written loop over it:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Joins the names of the in-stock products with ", ". Every use of the// iterator has the same hand-written shape: make it, ask has_next(),// call next(). No standard algorithm accepts that shape.std::string names_in_stock(const std::vector<Product>& products) { std::string names; InStockIterator it{products}; // already standing on the first in-stock product while (it.has_next()) { // Put ", " before every name except the first: the string is empty // only until the first name is added. if (!names.empty()) { names += ", "; } names += it.next().name; // next() hands out a product and moves past it } return names;}
// Counts the in-stock products. The for loop's three parts are: make the// iterator, keep going while has_next(), and step with next(). The product// next() returns is not needed here, so the loop just throws it away.std::size_t count_in_stock(const std::vector<Product>& products) { std::size_t count = 0; for (InStockIterator it{products}; it.has_next(); it.next()) { ++count; } return count;}How this code works: InStockIterator and names_in_stock
The iterator keeps one number, index_, and one promise: after the
constructor and after every next(), index_ stands on an in-stock
product, or on the end of the vector. skip_out_of_stock keeps that
promise by stepping past any product with no stock.
- The constructor stores a pointer to the vector, starts
index_at 0, and skips any out-of-stock products at the front. has_next()only checksindex_ < size, which is enough because of the promise.next()throwsstd::out_of_rangeif there is nothing left. Otherwise it takes a reference to the product atindex_, movesindex_on by one, skips again, and returns the reference it took before moving. The reference points into the caller’s vector, which is why that vector must outlive the iterator.
A trace with the catalogue in main (kettle 3 in stock, desk lamp 0,
notebook 12, office chair 2, lamp bulb 40):
| Step | index_ before |
Returns | index_ after |
names afterwards |
|---|---|---|---|---|
| constructor | 0 | - | 0 (kettle) | empty |
next() |
0 | kettle | 2 (skips desk lamp) | kettle |
next() |
2 | notebook | 3 | kettle, notebook |
next() |
3 | office chair | 4 | kettle, notebook, office chair |
next() |
4 | lamp bulb | 5 (the end) | kettle, notebook, office chair, lamp bulb |
Now has_next() is 5 < 5, false, and the loop ends. count_in_stock
walks the same steps and counts 4. The simple form below gives the same
two answers with no index and no promise to keep.
The simple form. The products are in a std::vector, which
already has iterators:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The same two functions with what std::vector already offers. These are// outside namespace pattern, so main can call both versions and compare.std::string names_in_stock(const std::vector<Product>& products) { std::string names; // Range-for: visit every product in order. `const Product&` reads each // one in place, without copying it. for (const Product& product : products) { if (in_stock(product)) { // `?:` picks "" for the first name and ", " for the rest; adding // the std::string name to it gives one string, which is appended. names += (names.empty() ? "" : ", ") + product.name; } } return names;}
// std::ranges::count_if calls in_stock on each product and counts the// trues. The function itself is passed, by name, as the test to apply.// count_if returns a signed count, so static_cast converts it to the// std::size_t this function promises; a count is never negative.std::size_t count_in_stock(const std::vector<Product>& products) { return static_cast<std::size_t>(std::ranges::count_if(products, in_stock));}A range-for loop with an if says “for each product in stock”.
std::ranges::count_if says “how many are in stock” in one call, with
the same in_stock function as its predicate.
Why the simple form fits here. The collection is a standard
container, and the order is its own order. The iterator class adds a
borrowed pointer that must not dangle, a precondition on next, and a
loop shape that no standard algorithm accepts. The range-for loop has
none of these.
When the pattern earns its place. The Iterator idea is still right
when your own type holds the elements in a way callers should not
see: a tree walked in order, results fetched page by page, a ring
buffer. Then write it the C++ way, as the
Iterator page shows: begin() and end() that
return iterators, so that range-for loops and the standard algorithms
work on it. A has_next/next class is the one form to avoid in
C++, because nothing in the standard library can use it.
3. Builder, or a struct with defaults
Section titled “3. Builder, or a struct with defaults”The pattern form. A search has a text, an optional maximum price, an “in stock only” flag, and a limit. A Builder gives each one a setter:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A Builder for the same query: one setter per member, then build().// Each setter stores its value in query_ and returns the builder itself// (a reference to *this), so calls can be chained on one line:// SearchQueryBuilder{}.text("lamp").max_price_cents(2500).build().// Members that no setter touches keep the SearchQuery defaults.class SearchQueryBuilder {public: // Takes the string by value and moves it into query_. SearchQueryBuilder& text(std::string value); SearchQueryBuilder& max_price_cents(int cents); // `= true` is a default argument: in_stock_only() means "yes". SearchQueryBuilder& in_stock_only(bool value = true); SearchQueryBuilder& limit(int count);
// Returns a copy of the finished query; the setters themselves accept // any value, so this is where the builder catches a bad one. SearchQuery build() const; // calls check, so a bad query is refused here
private: SearchQuery query_; // the query being filled in, starting at the defaults};A call reads
SearchQueryBuilder{}.text("lamp").max_price_cents(2500).in_stock_only().build().
The simple form. The query is plain settings, so make it a struct whose members all have defaults, and check it where it is used:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A product search. Every member has a default, so a caller names only// what it needs: SearchQuery{.text = "lamp", .in_stock_only = true}.// Those `.name = value` parts are C++20 designated initializers; the// names must come in the order the members are declared below, and any// member not named keeps its default. A struct has no constructor to// check its members, so the checking is done by check() instead.struct SearchQuery { std::string text = {}; // part of the name; empty matches every product // std::optional<int> either holds a price or holds nothing. `= {}` // starts it empty, which here means "no price limit", with no magic // value such as -1 standing in for "none". std::optional<int> max_price_cents = {}; // no maximum when empty bool in_stock_only = false; int limit = 20; // 1 to 100 results
// Equal when all four members are equal; the tests and main use it to // check that the Builder produces the very same query. bool operator==(const SearchQuery&) const = default;};
// Throws std::invalid_argument if the limit is outside 1 to 100 or the// maximum price is negative.void check(const SearchQuery& query);
// Checks the query, then returns the matching products in the order// given, at most query.limit of them. A product matches when its name// contains `text`, its price is at most the maximum (if there is one),// and, if in_stock_only is set, it is in stock. The results are copies.// Throws what check throws, before looking at any product.std::vector<Product> search(const std::vector<Product>& products, const SearchQuery& query);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Name the three members this search needs; limit keeps its default, 20.// 2500 goes into the std::optional<int>, so there is a maximum of 25.00.// search() checks the query first and throws std::invalid_argument if// it is bad. Here only "lamp bulb" matches: "desk lamp" costs 19.99 but// has no stock.const SearchQuery cheap_lamps{.text = "lamp", .max_price_cents = 2500, .in_stock_only = true};const std::vector<Product> found = search(catalogue, cheap_lamps);C++20 designated initializers name each member that is set, and
the rest keep their defaults. std::optional<int> says “there may be
no maximum” without a magic value such as -1. The builder above
builds exactly this struct, and the tests check that both give the
same query.
Why the simple form fits here. Every member is independent, every
one has a sensible default, and there are no steps. The struct is
shorter, can be compared with ==, and can be copied and stored as
it is. search calls check itself, so a bad query is
refused whichever way it was made.
The trade-off is that the struct has no invariant: anyone can set
limit = 0, and the mistake is found only when the query is used. The
Builder found it in build(). That is usually fine for settings that
go straight into one function; it is not fine for an object that is
stored and passed around for a long time.
When the pattern earns its place.
- The object must be valid from the moment it exists, and has many members. A class whose constructor checks them is the first step; a Builder helps when there are too many for one readable constructor.
- Construction has steps: “add a header”, “add another”, then “set the body and its type together”, with checks between steps. A struct can group the body and its type, but it cannot accumulate repeated parts or check one step against another.
- The same steps must produce different products, which is what Builder was first described for.
The Builder page makes the same choice for an HTTP request, and notes that the names must appear in declaration order.
4. State, or an enum class and a function
Section titled “4. State, or an enum class and a function”The pattern form. An order is placed, then paid, shipped, and delivered, and it can be cancelled before it ships. The State pattern gives each status a class, and the order holds the current one:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The State pattern for the same rules: one class per status.// Each state class answers two questions: "which status am I?" and "what// state comes after this event?". The rules are spread out, one class// at a time, instead of sitting together in one function.class OrderState {public: virtual ~OrderState() = default; virtual OrderStatus status() const = 0; // The next state, or null if `event` is not allowed in this one. // A new state object is made on the heap for every change, and the // caller owns it: that is what returning std::unique_ptr says. virtual std::unique_ptr<OrderState> on(OrderEvent event) const = 0;};
// One class per status. status() names it; on() is written in the .cpp// file: placed accepts pay or cancel, paid accepts ship or cancel, and// shipped accepts only deliver.class Placed final : public OrderState {public: OrderStatus status() const override { return OrderStatus::placed; } std::unique_ptr<OrderState> on(OrderEvent event) const override;};
class Paid final : public OrderState {public: OrderStatus status() const override { return OrderStatus::paid; } std::unique_ptr<OrderState> on(OrderEvent event) const override;};
class Shipped final : public OrderState {public: OrderStatus status() const override { return OrderStatus::shipped; } std::unique_ptr<OrderState> on(OrderEvent event) const override;};
// The two final states refuse every event, so on() always returns null.// The parameter has no name because it is never used.class Delivered final : public OrderState {public: OrderStatus status() const override { return OrderStatus::delivered; } std::unique_ptr<OrderState> on(OrderEvent) const override { return nullptr; }};
class Cancelled final : public OrderState {public: OrderStatus status() const override { return OrderStatus::cancelled; } std::unique_ptr<OrderState> on(OrderEvent) const override { return nullptr; }};
// The order itself: it owns exactly one current state object and swaps in// a new one each time an allowed event arrives.class Order {public: Order(); // starts placed
// Moves to the next state and returns true, or returns false and stays. // It asks the current state for the next one; a null answer means // "refused", and the current state is kept. bool handle(OrderEvent event); OrderStatus status() const;
private: // Never null, unless moved from; do not call handle or status on a moved-from Order. // The unique_ptr owns the state: replacing it deletes the old one. std::unique_ptr<OrderState> state_;};Five state classes and a base class, a std::unique_ptr per change
of status, and the rules
are spread across three on functions in the .cpp file.
The simple form. The statuses have no data of their own, and
each rule is one line. An enum class names them, and one function
holds every rule:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Where an order is in its life, and the things that can happen to it.// Plain enum class values: no data, no heap, cheap to copy and compare.enum class OrderStatus { placed, paid, shipped, delivered, cancelled };enum class OrderEvent { pay, ship, deliver, cancel };
// The word for a status or an event, such as "paid" or "cancel", for// printing. Two functions share the name `name`; the compiler picks one// by the argument's type (overloading). std::string_view is a read-only// view of text; here it views a string literal, which lives for the// whole program, so the view never dangles.std::string_view name(OrderStatus status);std::string_view name(OrderEvent event);
// The status after `event`, or std::nullopt if `event` is not allowed in `status`.std::optional<OrderStatus> after(OrderStatus status, OrderEvent event);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Every rule of the order's life in one function. In: the current status// and an event. Out: the next status, or std::nullopt ("no value") when// the event is not allowed now. Nothing is changed: the caller decides// what to do with the answer.// The switch picks the case for the current status; inside it, each `if`// tests one allowed event and returns at once. Reaching the end of a case// means no allowed event matched, so it returns std::nullopt.std::optional<OrderStatus> after(OrderStatus status, OrderEvent event) { switch (status) { case OrderStatus::placed: // Returning a plain OrderStatus fills the optional with it. if (event == OrderEvent::pay) { return OrderStatus::paid; } if (event == OrderEvent::cancel) { return OrderStatus::cancelled; } return std::nullopt; case OrderStatus::paid: if (event == OrderEvent::ship) { return OrderStatus::shipped; } if (event == OrderEvent::cancel) { return OrderStatus::cancelled; // the payment is refunded } return std::nullopt; case OrderStatus::shipped: if (event == OrderEvent::deliver) { return OrderStatus::delivered; } return std::nullopt; // Two case labels in a row share one body. case OrderStatus::delivered: case OrderStatus::cancelled: return std::nullopt; // final: nothing more can happen } // Every case above returns, so this line runs only for a value that is // not one of the five statuses (for example, a bad static_cast from an // int). Without it, the function could end without returning anything. throw std::invalid_argument{"after: not an order status"};}after returns std::optional<OrderStatus>: a next status, or
“nothing”, meaning the event is not allowed. The caller must look at
the result before using it:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The order's status is a plain variable; `events` is pay, ship, cancel,// deliver. history records what happened, starting with "placed".OrderStatus status = OrderStatus::placed;std::string history{name(status)}; // copies the string_view's text into a stringfor (const OrderEvent event : events) { // An if with a declaration: `next` is made from after(...), and the // if is taken when the optional holds a value. `next` exists only // inside this if and its else. if (const std::optional<OrderStatus> next = after(status, event)) { status = *next; // * reads the status out of the optional // std::string{...} turns the view into a string, so + can join. history += " -> " + std::string{name(status)}; } else { // Refused: the status stays as it was, and the refusal is noted. history += " (" + std::string{name(event)} + " refused)"; }}How this code works: the order's history loop
after never changes anything; it only answers “what would the status
be?”. The loop decides what to do with the answer.
historystarts asplaced.- For each event,
after(status, event)returns either a status orstd::nullopt. Theifdeclaresnextand tests it in one step: an optional that holds a value counts as true. - If there is a next status,
*nextreads it out,statustakes it, and->plus its name is added tohistory. - If not,
statusstays as it was, and the refusal is recorded in brackets.
The events in main are pay, ship, cancel, deliver:
| Event | status before |
after returns |
status after |
|---|---|---|---|
| pay | placed | paid | paid |
| ship | paid | shipped | shipped |
| cancel | shipped | std::nullopt |
shipped |
| deliver | shipped | delivered | delivered |
So history ends as placed -> paid -> shipped (cancel refused) -> delivered,
the line the program prints. Cancel is refused because the shipped
case only accepts deliver.
Why the simple form fits here. All the rules fit on one screen,
and they read like the state diagram. The status is a plain value: it
can be stored in a database column, compared, and copied, and it needs
no heap allocation. Because the switch has a case for every
enumerator and no default, GCC and Clang warn (with -Wall) if a
new status is added and not handled, so the compiler finds every place
that needs a new rule.
When the pattern earns its place. The State
page names the signs: some stages have data that means nothing in
the others (here, a tracking number once shipped, or a refund
reference once cancelled), the rules of one stage are long enough for their own class
and tests, or many operations each need a switch on the status.
When only the data differs, the std::variant form on that page is
the middle step; when the behaviour differs too, use the classes.
With many states and uniform rules, a transition table in data is
shorter still.
5. A class hierarchy, or a std::variant of values
Section titled “5. A class hierarchy, or a std::variant of values”The pattern form. Delivery can be to a home address, to a store for pickup, or to a parcel locker. A base class with two virtual functions, and one class per option:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The same three options as a class hierarchy.// The base class is an interface: two pure virtual functions (`= 0`) that// every option must supply. Code holds an option through a pointer or// reference to DeliveryOption, and each call runs the derived class's// version. Objects are usually kept in std::unique_ptr<DeliveryOption>,// so they cannot be copied or compared without extra code.class DeliveryOption {public: // Virtual, so deleting an option through a DeliveryOption pointer also // runs the derived class's destructor (and frees its string). virtual ~DeliveryOption() = default; virtual int fee_cents(int subtotal_cents) const = 0; virtual std::string describe() const = 0;};
// The three classes mirror the three structs above, but keep their data// private and give the behaviour as member functions. They have the same// names as the structs; namespace pattern keeps the two sets apart.class HomeDelivery final : public DeliveryOption {public: // The address is taken by value and moved into address_. explicit HomeDelivery(std::string address); int fee_cents(int subtotal_cents) const override; std::string describe() const override;
private: std::string address_;};
class StorePickup final : public DeliveryOption {public: explicit StorePickup(std::string store); int fee_cents(int subtotal_cents) const override; std::string describe() const override;
private: std::string store_;};
class Locker final : public DeliveryOption {public: explicit Locker(std::string locker_id); int fee_cents(int subtotal_cents) const override; std::string describe() const override;
private: std::string locker_id_;};Each option then lives behind a std::unique_ptr<DeliveryOption>,
cannot be copied without a clone function, and cannot be compared
without writing a comparison by hand.
The simple form. The three options are a fixed set, and each
is a little data. Make each one a struct, and the choice a
std::variant:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The three ways to get an order, each a small struct holding only the// data that option needs. No base class, no virtual functions: each is a// plain value with a defaulted ==.struct HomeDelivery { std::string address; bool operator==(const HomeDelivery&) const = default;};
struct StorePickup { std::string store; bool operator==(const StorePickup&) const = default;};
struct Locker { std::string locker_id; bool operator==(const Locker&) const = default;};
// A Delivery holds exactly one of the three, chosen when it is made:// `Delivery choice = Locker{"L-17"};` holds a Locker. The variant stores the// option inside itself (no pointer, no heap for the option), remembers// which one it holds, and can be copied and compared with == like the// structs. `using` gives the long type a short name.using Delivery = std::variant<HomeDelivery, StorePickup, Locker>;
// Home delivery costs 4.99 and is free from a 50.00 subtotal; pickup is// free; a locker costs 1.99.int delivery_fee_cents(const Delivery& delivery, int subtotal_cents);// "home delivery to 12 Elm Street", "pickup at Riverside", "locker L-17".std::string describe(const Delivery& delivery);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The fee for one delivery option, in cents. std::visit looks at which// struct the variant holds and calls the one lambda that takes that// struct. `overloaded` (defined above this snippet, in an unnamed// namespace) glues several lambdas into one object with one call// operator per lambda, so std::visit can choose among them by type.// Every lambda returns an int, so std::visit returns that int. There is// no catch-all lambda, so a fourth struct added to Delivery and not// handled here would make this call fail to compile.int delivery_fee_cents(const Delivery& delivery, int subtotal_cents) { return std::visit(overloaded{ // [subtotal_cents] copies the subtotal into this // lambda: only home delivery depends on it. // The parameter has no name: the fee does not // depend on the delivery address. [subtotal_cents](const HomeDelivery&) { return subtotal_cents >= free_home_delivery_from ? 0 : home_delivery_fee; }, [](const StorePickup&) { return 0; }, [](const Locker&) { return locker_fee; }, }, delivery);}
// The text for one option. Same shape: one lambda per struct, each using// that struct's own member. "home delivery to " + home.address joins a// string literal and a std::string, giving a std::string, so all three// lambdas return the same type, as std::visit requires.std::string describe(const Delivery& delivery) { return std::visit(overloaded{ [](const HomeDelivery& home) { return "home delivery to " + home.address; }, [](const StorePickup& pickup) { return "pickup at " + pickup.store; }, [](const Locker& locker) { return "locker " + locker.locker_id; }, }, delivery);}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Three different options stored directly in one vector, by value: each// struct is converted into a Delivery variant that holds it.const std::vector<Delivery> options{HomeDelivery{"12 Elm Street"}, StorePickup{"Riverside"}, Locker{"L-17"}};// For a subtotal of 34.97, below the 50.00 free-delivery line, the fees// print as 4.99, 0.00, and 1.99. money() formats cents as "4.99".for (const Delivery& option : options) { std::cout << describe(option) << ": " << money(delivery_fee_cents(option, 3497)) << '\n';}How this code works: std::visit with overloaded
- The variant knows which struct it holds. A
Deliverymade fromLocker{"L-17"}holds aLocker, and remembers that it does. overloaded{...}builds one object from three lambdas. It inherits from each lambda’s type and brings all three call operators into one place, so the object can be called with aHomeDelivery, aStorePickup, or aLocker, and C++ picks the matching lambda by the argument’s type, as it would for overloaded functions.std::visit(visitor, delivery)calls the visitor with a reference to the struct inside the variant (nothing is copied out). That runs exactly one lambda, and its result becomes the result ofstd::visit.- Only home delivery needs the subtotal, so only that lambda
captures
subtotal_cents, by copy.
With the subtotal 34.97 (3497 cents) that main uses:
| Option | Lambda that runs | Fee |
|---|---|---|
HomeDelivery |
3497 >= 5000 is false, so 499 |
4.99 |
StorePickup |
always 0 | 0.00 |
Locker |
always locker_fee, 199 |
1.99 |
With a subtotal of 5000, as the next line of main tries, home delivery
is free: 5000 >= 5000 is true, so the fee is 0.
Why the simple form fits here. A Delivery is a value: it is
copied, compared with ==, kept in a std::vector directly, and
stored in an order directly, with no std::unique_ptr and no
separate allocation for the option (the strings inside may still
allocate). Both functions are in one place, and since overloaded
(the helper from the Visitor
page) has no catch-all case, adding a
fourth option makes each std::visit that does not handle it fail to
compile.
When the pattern earns its place. When the set of kinds is open: delivery partners added by another team, or loaded at run time, need a base class that they can implement without editing the variant. The trade-off is the one the Visitor page describes: a variant makes adding an operation easy and adding a kind an edit to every visit; a class hierarchy is the reverse.
6. Observer with one listener, or a returned value
Section titled “6. Observer with one listener, or a returned value”The pattern form. Checking out works out a receipt, and the receipt printer is told through an Observer:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Observer, used where only one listener, the receipt printer, ever subscribes.// A listener is anything that wants to hear about a finished checkout: it// derives from this interface and supplies checked_out.class CheckoutListener {public: virtual ~CheckoutListener() = default; // Called for each checkout with its receipt. The reference is valid // only during the call; a listener that wants to keep it must copy it. virtual void checked_out(const Receipt& receipt) = 0;};
// The subject: it keeps a list of borrowed listeners and tells each of// them about every checkout, instead of handing the receipt back.class Checkout {public: // Borrows the listener, which must stay alive until it unsubscribes or // the Checkout is destroyed. Listeners must not subscribe or // unsubscribe while check_out is telling them. void subscribe(CheckoutListener& listener); void unsubscribe(CheckoutListener& listener);
// Works out the receipt and tells every listener, in the order they // subscribed; returns nothing. If a listener throws, later ones are not told. void check_out(const std::vector<CartLine>& cart, const Delivery& delivery);
private: std::vector<CheckoutListener*> listeners_; // borrowed, never null};
// The one listener in this program. checked_out formats the receipt and// keeps the text, so main and the tests can read it back afterwards.class ReceiptPrinter final : public CheckoutListener {public: void checked_out(const Receipt& receipt) override; // Empty until the first checkout; a later checkout replaces it. const std::string& last_printed() const;
private: std::string last_printed_;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Local objects are destroyed in reverse order of declaration, so// checkout (declared second) goes first, while printer still exists.pattern::ReceiptPrinter printer; // declared first, so it outlives its subscriptionpattern::Checkout checkout;checkout.subscribe(printer); // checkout stores &printer; it does not own it// Nothing comes back: the receipt goes to printer.checked_out, and the// text is read later with printer.last_printed().checkout.check_out(cart, Locker{"L-17"});In this program, the printer is the only listener, it subscribes
once, and it wants the receipt straight away. Yet the design must
still answer Observer’s questions: the printer must outlive its
subscription (so it is declared first), and listeners must not
subscribe or unsubscribe during check_out, a rule that only a
comment enforces.
The simple form. Return the receipt to the caller, who prints it:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One line in the cart: what, the price of one, and how many.struct CartLine { std::string name; int unit_price_cents = 0; int quantity = 0;};
// The result of checking out, as a plain value. The total is not stored:// total_cents() works it out each time, so it can never disagree with// the two parts. The defaulted == lets a test compare a whole receipt in// one check.struct Receipt { int subtotal_cents = 0; int delivery_cents = 0; std::string delivery; // as describe() shows it
int total_cents() const { return subtotal_cents + delivery_cents; } bool operator==(const Receipt&) const = default;};
// The simple form: work out the receipt and return it. The subtotal is the// sum of price times quantity over the lines; the delivery fee and text// come from delivery_fee_cents and describe. No listeners and no stored// state: the caller gets the result and decides what to do with it.// Throws std::invalid_argument for an empty cart, a quantity below 1, or// a negative price. Amounts are assumed small enough not to overflow.Receipt check_out(const std::vector<CartLine>& cart, const Delivery& delivery);
// "subtotal 44.96 + locker L-17 1.99 = 46.95"std::string format_receipt(const Receipt& receipt);
// "12.50" for 1250, "0.05" for 5; throws std::invalid_argument for a// negative amount.std::string money(int cents);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The cart is 3 notebooks at 4.99 and a kettle at 29.99: 44.96. The// Locker{"L-17"} temporary becomes a Delivery for the call. The result// comes straight back, and the caller prints it.const Receipt receipt = check_out(cart, Locker{"L-17"});std::cout << format_receipt(receipt) << '\n';Why the simple form fits here. The caller is the one party that
wants the result, and wants it now. A return value carries it with no
borrowed pointers, no subscription, and no order of destruction to get
right. check_out is also easier to test: call it, then compare the
Receipt it returns, which has a defaulted ==.
When the pattern earns its place. When several parts that the subject must not know about react to the same event, and that list changes: a receipt printer, an e-mail sender, and stock updates, owned by different teams. The Observer vs Mediator page compares the shapes. Even with two known reactions, first try calling two functions from the code that made the receipt; reach for Observer when the subject must not depend on its listeners.
Running the example
Section titled “Running the example”The program runs each simple form, then checks that its pattern form gives the same result:
cheapest first: lamp bulb, notebook, desk lamp, kettle, office chairbest rated, then cheapest: lamp bulb, desk lamp, notebook, kettle, office chairthe Strategy version agrees: yesin stock: kettle, notebook, office chair, lamp bulb (4)the Iterator version agrees: yeslamps up to 25.00, in stock: lamp bulbthe Builder makes the same query: yesrefused: search: limit must be 1 to 100order: placed -> paid -> shipped (cancel refused) -> deliveredthe State version ends the same way: yeshome delivery to 12 Elm Street: 4.99pickup at Riverside: 0.00locker L-17: 1.99home delivery from 50.00: 0.00the class hierarchy agrees: yessubtotal 44.96 + locker L-17 1.99 = 46.95the Observer version prints the same: yesReading the output:
- “cheapest first” comes from the projection, “best rated, then
cheapest” from the lambda. The desk lamp and the lamp bulb both have
five stars, so the cheaper bulb comes first. The
BestRatedThenCheapestclass gives the same order. - Four of the five products are in stock; the desk lamp is not. The
loop,
count_if, and the iterator class agree. - The search for lamps up to 25.00 that are in stock finds only the
lamp bulb, because the desk lamp is out of stock. The builder makes a
query equal to the struct, and a query with
limit = 0is refused bycheck, insidesearch. - The order goes from placed to paid to shipped, refuses the cancellation (it has shipped), and is delivered. The State classes end in the same status.
- For an example subtotal of 34.97, under 50.00, home delivery costs 4.99; pickup is free, and the locker costs 1.99. From 50.00, home delivery is free. The class hierarchy gives the same fees and descriptions.
- Three notebooks at 4.99 and a kettle at 29.99 make 44.96; the locker
adds 1.99. The printer told by the Observer prints the same text as
the caller that received the
Receipt.
Summary table
Section titled “Summary table”| Pattern form | Simple form | Switch to the pattern when… |
|---|---|---|
| Strategy interface | a lambda or projection passed to the algorithm | each choice has several related functions, or comes from a plug-in |
has_next/next iterator |
range-for loop, standard algorithm | your own type hides its storage: give it begin() and end() |
| Builder | struct with defaults, designated initializers, check |
the object needs an invariant from birth, or construction has steps |
| State classes | enum class and a function returning std::optional |
stages have their own data, or long rules of their own |
| Class hierarchy | std::variant of small structs |
the set of kinds is open to other teams or to run time |
| Observer with one listener | a returned value | several unknown parts react, and the subject must not depend on them |
When the requirements change
Section titled “When the requirements change”- “Let users pick a sort order and remember it.” The order now has
a name that is saved and shown. A small
enum class SortOrderand a function that returns the comparison for each value keeps it simple; it becomes a Strategy only if each order gains several functions. - “Search from the URL’s parameters.” Still a struct: the parser
fills its members one by one, then calls
check. That is not a Builder, because nothing needs to be enforced between steps. - “Show the tracking number once an order has shipped.” The
Shippedstage now has data that the others do not. Either keep theenum classand add astd::optional<std::string> tracking_numberto the order, which allows a placed order with a tracking number, or move to thestd::variantform of State, where onlyShippedhas one. With several such fields, the variant form is safer. - “A partner team adds same-day couriers.” The set of delivery
kinds is now open, so the
DeliveryOptioninterface earns its place. - “E-mail the receipt as well.” Two reactions, both known: call
printandemailaftercheck_outreturns. If the list keeps growing, or the code that checks out must not depend on the e-mail service, introduce Observer then.
Common mistakes
Section titled “Common mistakes”- Replacing a pattern with a worse simple form. A
switchon the same enum in ten functions is not simpler than State; it is the problem State solves. Count the places that would change when a new kind is added. - A lambda that outlives what it captures. A lambda stored for
later, with
[&], can dangle exactly like a borrowed pointer. The simple forms here are used at once; when you store one, capture by value or state who outlives whom. std::optionalfor an error with a reason.afterreturns “nothing” because there is only one reason an event is refused. When the caller needs to know why, throw an exception with a message, or return a type that holds the error.- A struct for an object with rules. Settings that go straight into one function can be a struct. An object passed around and kept for a long time should not let anyone break it; give it a constructor that checks.
- Keeping both forms. Once you choose, delete the other. The example keeps both only so the tests can compare them.
C++ notes
Section titled “C++ notes”- Designated initializers (C++20) must name members in declaration
order. With
-Wextra, GCC 11 warns about any member that a designated initializer leaves out and that has no default member initializer, even astd::string. That is why every member ofSearchQueryhas one, written= {}where the default is empty. switchon anenum classwith nodefaultgets a-Wswitchwarning for each missing enumerator. The function still needs something after theswitch(here athrow): anenum classvariable can hold a value that is not one of its enumerators, and flowing off the end of a non-void function is undefined behaviour. GCC warns about that path (-Wreturn-type); Clang 14 does not when every enumerator has a case.- Projections such as
&Product::price_centswork with thestd::rangesalgorithms, and save writing a lambda that compares one member. - Range views such as
std::views::filtercan express the in-stock loop too. This example uses only the algorithms: with this project’s Clang 14 and the GCC 12 standard library that it uses,views::filterdoes not compile.
Exercise
Section titled “Exercise”Exercise: Pattern or not? Six decisions
For each situation, choose a pattern or a simpler form, and say what fact about the problem decides it. Where an object is shared or borrowed, say who owns it.
- A log viewer filters lines. Each screen passes its own filter, such as “errors only” or “contains this word”, and uses it once.
- A payment service supports cards, a wallet, and bank transfers. Other teams add new providers as plug-ins, loaded at start-up. Each provider must authorise, capture, and refund.
- A traffic light is red, green, or amber, and moves to the next colour on a timer. The colours have no data of their own.
- A thumbnail generator takes a width, a height, a quality from 1 to 100, and an output format; each has a default.
- A spreadsheet cell changes. Charts, dependent formulas, and the undo history must react; they are written by different teams, and more kinds of reaction are planned.
find_user(id)might find nobody. A colleague proposes aNullUserclass whose functions do nothing, so that callers need no check.
Show the explained answer
- A lambda, or a
std::functionparameter if the filter is stored. The filter is one call, chosen by the caller, used at once: question 1. ALineFilterinterface would add a class per filter for nothing.std::ranges::copy_ifor a loop with the lambda does the work. If the filter is stored, for example in astd::function, and captures the search word, capture it by value so the stored filter owns its copy. A filter used at once can capture by reference. - An interface: the pattern earns its place. Each provider is a
role with three related functions, and the set is open,
because other teams add providers without editing your code. A
std::variantwould force them to edit it. The service owns each provider as astd::unique_ptr<PaymentProvider>, created by the plug-in loader at start-up. The plug-in library must stay loaded until every provider it created has been destroyed, so the service destroys its providers before the loader unloads the libraries. - An
enum classand anextfunction. A small life cycle with no data per stage: question 4.Color next(Color)with aswitchis the whole design, and the compiler warns if a colour is added and not handled. The timer callsnext; the light owns its current colour as a plain value. - A struct with defaults, and a check. Plain settings, each with
a default: question 3.
ThumbnailOptions{.width = 200, .quality = 80}reads clearly. The generator checks the quality range when it is called, or the struct becomes a class with a checking constructor if options are stored and passed around. The format could be anenum class, which needs no range check when callers use its enumerators. - Observer. Several reactions, owned by other teams, that the cell must not know about, with more on the way: the “no” to question 6. The cell owns its subscription list; each subscriber must unsubscribe before it is destroyed, ideally through a subscription object that does it in its destructor, as the Observer page shows. Re-entrancy (a formula changing another cell while it is being told) needs a rule.
std::optional<User>(or a pointer that may be null), not a Null Object. “Nobody found” is a real answer that callers usually must handle: showing “no such user” is not the same as doing nothing. ANullUserwould let a caller carry on as if it had found someone, and hide the mistake. A Null Object fits when doing nothing is the right behaviour for every caller, such as a logger that discards messages in tests. Withstd::optional<User>, the caller owns the copy it receives; if users are large and owned by a cache, returnconst User*, borrowed from the cache, and state how long it stays valid.
Summary
Section titled “Summary”- Ask what the pattern gives this problem that a lambda, a loop, a
struct, an
enum class, astd::variant, or a return value does not. - The standard library already contains several patterns: a sort’s comparison is a Strategy, a container’s iterators are an Iterator.
- The simple forms work best for things that are one call, closed, plain data, or only the caller’s business.
- Patterns earn their place when something is open to other code, has several related functions, needs an invariant, or must reach listeners the subject must not know.
- Changing your mind later is cheap in both directions when the code is small, so start simple and move to the pattern when a real requirement asks for it.