Early previewThis guide is in development. Items tagged verify are still being checked against official docs.
nebx Learn
GitHub
Menu
C++

C++

Zero-cost abstractions and full control over memory.

Paradigm
Multi-paradigm, OOP, generic
Typing
Static, strong-ish
Memory
Manual / RAII, no GC
Runs
Native machine code (AOT)
Concurrency
Threads, atomics, coroutines (C++20)
Creational pattern

Builder

Intent

Constructs complex objects step by step, letting the same process produce different representations.

Problem

A constructor with ten optional parameters is unreadable, and most calls pass null.

Solution

Move construction into a builder object with methods for each step; call only the steps you need, then build().

Real-world analogy

Think of it like this

Ordering a custom burger: you pick the bun, patty and toppings step by step, while the cook (the director) also knows a few standard recipes.

Structure

association / extends implements / depends on
Director - builder: Builder+ make(type) 4 «interface» Builder + reset()+ buildStepA()+ buildStepB() 1 ConcreteBuilder1 - result: Product1+ buildStepA()+ getResult(): Product1 2 Product1 3 Client + main() 5

Hover or tap a numbered role to highlight it in the diagram.

  1. 1Builder — Builder declares the construction steps common to all builders.
  2. 2ConcreteBuilder1 — Concrete Builders implement the steps and can produce products that don't share an interface.
  3. 3Product1 — Products are the resulting objects.
  4. 4Director — Director (optional) defines the order of steps so recipes can be reused.
  5. 5Client — Client creates a builder, passes it to the director, then gets the result from the builder.

Code example

A C++ code sample for Builder is coming soon. Factory Method, Singleton, Decorator, Observer and Strategy already have code in all six languages.

Applicability

Use Builder when getting rid of telescoping constructors.

Use Builder when creating different representations of a product.

Use Builder when building composite trees.

Pros and cons

Pros

  • Step-by-step, deferrable construction
  • Reuse the same construction code

Cons

  • More classes and code

Relations with other patterns

Check yourself

Check yourself

You need to assemble SQL queries with optional WHERE, JOIN, ORDER BY and LIMIT parts in any combination.

Saved in this browser only. Part of Creational patterns (0/5).