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
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
Hover or tap a numbered role to highlight it in the diagram.
- 1Builder — Builder declares the construction steps common to all builders.
- 2ConcreteBuilder1 — Concrete Builders implement the steps and can produce products that don't share an interface.
- 3Product1 — Products are the resulting objects.
- 4Director — Director (optional) defines the order of steps so recipes can be reused.
- 5Client — Client creates a builder, passes it to the director, then gets the result from the builder.
Code example
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
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).