design patterns · creational

Builder

Separates the construction of a complex object from its representation using a step-by-step builder API.

easycreational0.5h
Ask GPTConfidence

Pattern

Overview

Intent

Separate the construction of a complex object from its representation so the same construction process can create different representations.

Real-World Analogy

Ordering a custom sandwich: you choose bread, filling, toppings step-by-step. The cashier (Director) follows your order; the kitchen (Builder) assembles it.

When constructing an object requires many optional parameters, a constructor with 10 arguments is unreadable. Builder solves this with a fluent API: Pizza.Builder("Large").cheese().pepperoni().build().

A Builder class accumulates parameters via method chaining. The final build() call constructs and returns the immutable product. An optional Director class encapsulates common build sequences.

When to use

HTTP request objects, SQL query builders, configuration objects, test data builders. Any object with 4+ optional parameters.

When not to

Objects with 1-3 parameters - a constructor or static factory is simpler. Mutable objects that need frequent partial updates.

Participants

BuilderConcreteBuilderDirectorProduct

Key Insights

  • Each setter returns this (or the Builder) to enable method chaining
  • build() is the natural place to validate mandatory fields and invariants
  • The Director is optional - clients can call builder methods directly
  • Builder produces immutable products naturally - all fields set before construction completes