Builder Pattern

Build a complex object step by step through a builder, so many optional parts do not turn into a constructor nobody can read.

Overview

Builder is a creational pattern from the Gang of Four book (Gamma, Helm, Johnson and Vlissides, *Design Patterns*, 1994). The idea: when an object takes many steps to assemble, put those steps on a separate builder object, and let the builder hand over the finished product at the end. The same sequence of steps can then produce different results, depending on which builder runs them.

In interviews the name covers two shapes. The GoF shape has a Director that knows the order of steps and a Builder interface with one method per step; different concrete builders produce different representations. The fluent shape, which Joshua Bloch popularized for Java in *Effective Java* (Item 2), has no director: the client chains setter-like methods on the builder and calls build(). Most interview questions mean the fluent one, and the strong answer knows both.

The pattern earns its place when a constructor would need many parameters, most of them optional, or when the product should be immutable once built.

The two shapes of the pattern

Start with the GoF shape, because it shows the roles. A Director calls the steps in order on a builder interface, and two concrete builders turn the same steps into an HTML report and a plain-text report.

The fluent builder differs on every point. In the GoF builder a Director orders the steps; in the fluent builder the client does, by chaining calls. The GoF builder exists because the same steps must produce different representations; the fluent one exists because one class has many optional parts. The GoF builder interface is shared by several concrete builders, while a fluent builder serves one product and is often nested in it. A GoF builder typically produces a document, a parse tree or a UI; a fluent builder produces a request, a configuration or a value object. And when an interviewer says 'builder', they rarely mean the GoF shape and almost always mean the fluent one.

Interview questions

  • What problem does Builder solve? Show the smell and the fix.
  • How do you make sure required fields are set before build()?
  • When does the GoF Director shape pay off?
  • How is Builder different from Factory Method and Abstract Factory?
  • Why pair a builder with an immutable product, and what does that mean for threads?

Sign up free to read the full topic

More Low-Level Design topics

Start free on Cariara · Coding problems · System design studio