Java Reference ยท Object-Oriented Concepts
The Builder pattern in Java
Reference for the Java builder pattern: fluent builders for objects with many optional fields, validation in build(), immutability, and records as targets.
The builder pattern separates the construction of an object from its final form. You collect values step by step in a mutable builder, then call build() to get an immutable result. It shines when a class has many optional parameters, because a constructor with eight arguments is unreadable (new Pizza(12, true, false, null, 2)) and telescoping constructors multiply quickly.
A fluent builder returns this from every setter-like method so calls chain. Validation belongs in build() (or the target's constructor), the one place that sees the complete set of values.
Pizza p = new Pizza.Builder("margherita").size(12).extraCheese().build();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Structure
| Part | Role |
|---|---|
| Product | The immutable class being built; its constructor is private or package-private and takes the builder. |
| Builder | A (usually static nested) class with mutable fields, defaults, and chainable methods. |
build() |
Validates the combined state and creates the product. |
| Factory method | Product.builder() hides the new Builder() call and reads well. |
Usage notes
- Validate in
build(). Individual setters cannot know about cross-field rules such as "end must be after start". - Required values can go into the builder's constructor (as
nameabove) so they cannot be forgotten. - Builders are not thread-safe and are normally used once. Do not share one between threads.
- Copy mutable parts (lists, arrays) when constructing the product, so later builder calls cannot change an already built object.
- Records are good targets: the canonical constructor does the validation, the builder only collects values. For records with two or three components a builder is overkill.
- Alternatives: static factory methods with named intent, overloaded constructors, or "wither" methods returning copies. Choose a builder when parameters are numerous and mostly optional.
- Libraries: Lombok's
@Builderand IDE generators write the boilerplate; the JDK hasStringBuilder,Stream.builder(),HttpRequest.newBuilder(),ProcessBuilderandLocale.Builder. - Inheritance needs a self-typed generic builder (
B extends Builder<B>), which gets complicated; prefer composition.