Creational Patternshigh

Builder Pattern

Separate the construction of a complex object from its representation, allowing the same construction process to create different representations. Eliminates telescoping constructors.

Memory anchor

Builder = Subway sandwich artist. You pick bread, then meat, then cheese, then veggies, then sauce — step by step. At the end they wrap it up (build()). You never get a half-made sandwich thrown at you.

Expected depth

Builder is most valuable when a class has many optional parameters. Instead of constructors with 8 arguments (most null), a Builder accumulates parameters and constructs the object only when build() is called. Fluent builders enable readable, named-parameter-style construction: new Pizza.Builder().size(LARGE).crust(THIN).addTopping(CHEESE).build(). The builder can validate invariants in build() before object creation — fail fast, not at use time.

Deep — senior internals

Builder has two forms: (1) the GoF Director/Builder/Product trio for constructing complex composite objects step-by-step; (2) the modern fluent/item builder (Joshua Bloch's Effective Java Item 2) for optional parameter management. The GoF form is used in document builders (HTML, SQL query builders, protobuf builders). The fluent form is ubiquitous in modern APIs (Retrofit, OkHttp, Spring Security). A key design decision: whether the Builder is a static nested class of the Product (preferred for encapsulation — access to private fields) or a separate class. Immutability: Builder pattern is the primary way to construct immutable objects with many fields — all fields are set on the builder, and build() creates a final, unmodifiable Product.

🎤Interview-ready answer

Builder solves two problems: telescoping constructors (8-argument overloads) and invalid intermediate state (an object that is partially constructed). I put a static Builder nested class in the Product. Each setter returns this for chaining. build() validates all required fields and invariants before calling the Product's private constructor. The object is immutable after construction. I always mention the validation opportunity in build() — it is the key advantage over setting fields directly or using a no-arg constructor with setters.

Common trap

Builder is not the same as a factory. Factory decides which type to create; Builder constructs one specific type step-by-step. The interviewer may ask when to prefer Builder over a factory — the answer is when the same type has many construction variants driven by parameter choices, not by polymorphic type selection.

Related concepts