Simple definition#
The Builder pattern constructs a complex object step by step, instead of in one constructor call. The construction logic lives in a separate builder object, so the same steps can produce a valid, often immutable, result.
GoF intent: “Separate the construction of a complex object from its representation so that the same construction process can create different representations.”
In Java you will meet two forms, and it is worth knowing both:
| Form | What it solves | Typical example |
|---|---|---|
| GoF Builder | One construction process producing different representations | A director builds release notes as Markdown or HTML |
| Fluent (“Effective Java”) builder | Readable, validated creation of an object with many optional fields | HttpRequest.newBuilder().uri(...).timeout(...).build() |
The problem#
Many optional parameters#
A product search has one required field (the text) and several optional ones (category, price range, sort order, page size). Constructors scale badly:
// Telescoping constructors: which argument is which?
new SearchQuery("laptop", "computers", null, new BigDecimal("1500"), Sort.PRICE_ASC, 20);
Positional nulls are unreadable, and two adjacent BigDecimal parameters are easy to swap. The JavaBeans alternative — a no-argument constructor plus setters — makes the object mutable and allows it to exist in a half-initialised, invalid state.
One process, several outputs#
Release notes must be published as Markdown for the repository and HTML for the website. The structure — title, features section, fixes section — is identical; only the output format differs. Duplicating the structure in two renderers means every structural change must be made twice.
Real-world analogy#
Ordering at a sandwich counter. You state the bread, then the filling, then the extras, one step at a time; the sandwich is handed over only when you say “that’s it”. Different counters (builders) follow the same ordering process but produce a wrap or a baguette.
Structure#
GoF form#
- Builder — interface with one method per construction step (
DocumentBuilder). - ConcreteBuilder — implements the steps for one representation and returns the result (
MarkdownBuilder,HtmlBuilder). - Director — knows the order of steps, not the representation (
ReleaseNotesDirector). - Product — the result (
Stringhere: a Markdown or HTML document).
classDiagram
direction LR
class ReleaseNotesDirector {
+construct(Release, DocumentBuilder~T~) T
}
class DocumentBuilder~T~ {
<<interface>>
+title(String) DocumentBuilder~T~
+section(String) DocumentBuilder~T~
+bullet(String) DocumentBuilder~T~
+build() T
}
class MarkdownBuilder {
-StringBuilder out
}
class HtmlBuilder {
-StringBuilder out
-boolean listOpen
}
ReleaseNotesDirector ..> DocumentBuilder : drives
DocumentBuilder <|.. MarkdownBuilder
DocumentBuilder <|.. HtmlBuildersequenceDiagram
participant Client as BuilderDemo
participant D as ReleaseNotesDirector
participant B as HtmlBuilder
Client->>D: construct(release, new HtmlBuilder())
D->>B: title("Release 2.4.0")
D->>B: section("New features")
D->>B: bullet("Export to JSON")
D->>B: bullet("Dark mode")
D->>B: section("Bug fixes")
Note over B: closes the open list before the new heading
D->>B: bullet("Fix rounding in totals")
D->>B: build()
B-->>D: HTML string
D-->>Client: HTML stringFluent form#
The fluent builder is a static nested class with the same fields as the target. Each setter-like method returns this, and build() validates the combination and calls a private constructor.
classDiagram
direction LR
class SearchQuery {
-String text
-String category
-BigDecimal minPrice
-BigDecimal maxPrice
-Sort sort
-int pageSize
-SearchQuery(Builder)
+builder(String)$ Builder
}
class Builder {
+category(String) Builder
+priceBetween(BigDecimal, BigDecimal) Builder
+sort(Sort) Builder
+pageSize(int) Builder
+build() SearchQuery
}
SearchQuery .. Builder : static nested class
Builder ..> SearchQuery : createsJava implementation#
The code is in examples/java/src/hub/patterns/builder/, compiled and run by CI with Java 21.
Fluent builder for an immutable object#
package hub.patterns.builder;
import java.math.BigDecimal;
import java.util.Objects;
import java.util.Optional;
/**
* An immutable value with one required field and several optional ones,
* built with a fluent builder (the "Effective Java" style of Builder).
*/
public final class SearchQuery {
public enum Sort { RELEVANCE, PRICE_ASC, PRICE_DESC, NEWEST }
private final String text; // required
private final String category; // optional
private final BigDecimal minPrice; // optional
private final BigDecimal maxPrice; // optional
private final Sort sort;
private final int pageSize;
private SearchQuery(Builder b) {
this.text = b.text;
this.category = b.category;
this.minPrice = b.minPrice;
this.maxPrice = b.maxPrice;
this.sort = b.sort;
this.pageSize = b.pageSize;
}
public static Builder builder(String text) {
return new Builder(text);
}
public String text() { return text; }
public Optional<String> category() { return Optional.ofNullable(category); }
public Optional<BigDecimal> minPrice() { return Optional.ofNullable(minPrice); }
public Optional<BigDecimal> maxPrice() { return Optional.ofNullable(maxPrice); }
public Sort sort() { return sort; }
public int pageSize() { return pageSize; }
@Override
public String toString() {
return "SearchQuery[text=" + text
+ category().map(c -> ", category=" + c).orElse("")
+ minPrice().map(p -> ", min=" + p).orElse("")
+ maxPrice().map(p -> ", max=" + p).orElse("")
+ ", sort=" + sort + ", pageSize=" + pageSize + "]";
}
public static final class Builder {
private final String text;
private String category;
private BigDecimal minPrice;
private BigDecimal maxPrice;
private Sort sort = Sort.RELEVANCE; // sensible defaults live in one place
private int pageSize = 20;
private Builder(String text) {
this.text = Objects.requireNonNull(text, "text");
}
public Builder category(String category) {
this.category = category;
return this;
}
public Builder priceBetween(BigDecimal min, BigDecimal max) {
this.minPrice = min;
this.maxPrice = max;
return this;
}
public Builder sort(Sort sort) {
this.sort = Objects.requireNonNull(sort, "sort");
return this;
}
public Builder pageSize(int pageSize) {
this.pageSize = pageSize;
return this;
}
/** Validates the combination of fields once, then creates the immutable object. */
public SearchQuery build() {
if (text.isBlank()) {
throw new IllegalStateException("search text must not be blank");
}
if (pageSize < 1 || pageSize > 100) {
throw new IllegalStateException("pageSize must be between 1 and 100");
}
if (minPrice != null && maxPrice != null && minPrice.compareTo(maxPrice) > 0) {
throw new IllegalStateException("minPrice must not exceed maxPrice");
}
return new SearchQuery(this);
}
}
}GoF builder: interface, concrete builders, director#
package hub.patterns.builder;
/**
* GoF Builder interface: the construction steps for a document,
* independent of the representation that is produced.
*/
public interface DocumentBuilder<T> {
DocumentBuilder<T> title(String text);
DocumentBuilder<T> section(String heading);
DocumentBuilder<T> bullet(String text);
/** Returns the finished product. */
T build();
}package hub.patterns.builder;
/** Concrete builder: produces Markdown text. */
public final class MarkdownBuilder implements DocumentBuilder<String> {
private final StringBuilder out = new StringBuilder();
@Override
public MarkdownBuilder title(String text) {
out.append("# ").append(text).append("\n");
return this;
}
@Override
public MarkdownBuilder section(String heading) {
out.append("\n## ").append(heading).append("\n");
return this;
}
@Override
public MarkdownBuilder bullet(String text) {
out.append("- ").append(text).append("\n");
return this;
}
@Override
public String build() {
return out.toString();
}
}package hub.patterns.builder;
/** Concrete builder: produces HTML. Tracks whether a list is open. */
public final class HtmlBuilder implements DocumentBuilder<String> {
private final StringBuilder out = new StringBuilder();
private boolean listOpen;
@Override
public HtmlBuilder title(String text) {
out.append("<h1>").append(escape(text)).append("</h1>\n");
return this;
}
@Override
public HtmlBuilder section(String heading) {
closeList();
out.append("<h2>").append(escape(heading)).append("</h2>\n");
return this;
}
@Override
public HtmlBuilder bullet(String text) {
if (!listOpen) {
out.append("<ul>\n");
listOpen = true;
}
out.append(" <li>").append(escape(text)).append("</li>\n");
return this;
}
@Override
public String build() {
closeList();
return out.toString();
}
private void closeList() {
if (listOpen) {
out.append("</ul>\n");
listOpen = false;
}
}
private static String escape(String s) {
return s.replace("&", "&").replace("<", "<").replace(">", ">");
}
}package hub.patterns.builder;
import java.util.List;
/**
* GoF Director: knows the construction *sequence* for release notes,
* but not the output format. Any DocumentBuilder can be plugged in.
*/
public final class ReleaseNotesDirector {
public record Release(String version, List<String> features, List<String> fixes) {
}
public <T> T construct(Release release, DocumentBuilder<T> builder) {
builder.title("Release " + release.version());
if (!release.features().isEmpty()) {
builder.section("New features");
release.features().forEach(builder::bullet);
}
if (!release.fixes().isEmpty()) {
builder.section("Bug fixes");
release.fixes().forEach(builder::bullet);
}
return builder.build();
}
}Running it#
package hub.patterns.builder;
import java.math.BigDecimal;
import java.util.List;
public final class BuilderDemo {
public static void main(String[] args) {
// 1. Fluent builder for an immutable object with optional fields.
SearchQuery query = SearchQuery.builder("laptop")
.category("computers")
.priceBetween(new BigDecimal("500"), new BigDecimal("1500"))
.sort(SearchQuery.Sort.PRICE_ASC)
.build();
System.out.println(query);
SearchQuery minimal = SearchQuery.builder("usb cable").build();
System.out.println(minimal);
try {
SearchQuery.builder("phone").pageSize(500).build();
} catch (IllegalStateException e) {
System.out.println("Rejected: " + e.getMessage());
}
// 2. GoF Builder: same construction process, two representations.
var release = new ReleaseNotesDirector.Release("2.4.0",
List.of("Export to JSON", "Dark mode"),
List.of("Fix rounding in totals"));
var director = new ReleaseNotesDirector();
System.out.println(director.construct(release, new MarkdownBuilder()));
System.out.print(director.construct(release, new HtmlBuilder()));
}
}SearchQuery[text=laptop, category=computers, min=500, max=1500, sort=PRICE_ASC, pageSize=20]
SearchQuery[text=usb cable, sort=RELEVANCE, pageSize=20]
Rejected: pageSize must be between 1 and 100
# Release 2.4.0
## New features
- Export to JSON
- Dark mode
## Bug fixes
- Fix rounding in totals
<h1>Release 2.4.0</h1>
<h2>New features</h2>
<ul>
<li>Export to JSON</li>
<li>Dark mode</li>
</ul>
<h2>Bug fixes</h2>
<ul>
<li>Fix rounding in totals</li>
</ul>Step-by-step walkthrough#
- Required parameters go into the builder’s constructor.
SearchQuery.builder("laptop")cannot be called without search text, so a missing required value is a compile error rather than a runtime surprise. - Defaults live in the builder.
sort = RELEVANCEandpageSize = 20are declared once. Callers state only what differs from the defaults. - Named methods replace positional arguments.
priceBetween(min, max)groups two related values, which makes them harder to misuse than two separateBigDecimalconstructor arguments. build()validates the whole object at once. Cross-field rules such as “min must not exceed max” can only be checked when all fields are known. An invalid query never exists.- The product is immutable.
SearchQueryhas onlyfinalfields and a private constructor, so it is thread-safe and can be shared freely. - The GoF director owns the sequence.
ReleaseNotesDirectordecides that features come before fixes and that empty sections are skipped. A new format, such as AsciiDoc, needs a new builder only. - Concrete builders own representation details.
HtmlBuildertracks whether a<ul>is open and escapes text. The director never sees these details.
Advantages and disadvantages#
| Advantages | Disadvantages |
|---|---|
| Readable creation code with named steps | More code: the builder duplicates the target’s fields |
| Supports immutability and validation of the complete object | Missing required fields are only caught at build(), unless they go in the builder’s constructor |
| Sensible defaults in one place | A builder for a three-field object is ceremony |
| GoF form: one construction process, many representations | GoF form: adds a director and a builder hierarchy |
When to use it#
- An object has four or more parameters, several of them optional (Bloch’s rule of thumb).
- Objects must be immutable and valid from the moment they exist.
- The same construction steps must produce different representations (GoF form): documents, reports, test fixtures, SQL dialects.
- Test data builders:
anOrder().withLines(2).paid().build()makes tests readable.
When not to use it#
- The object has a few required fields — use a constructor or a record.
- The object is mutable configuration that is changed after creation anyway.
- Code generation such as Lombok’s
@Builderwould hide validation you actually need. Generated builders do not validate cross-field rules unless you add them.
Common implementation mistakes#
- Reusing a builder after
build(). A mutable builder used twice can leak state between products. Either document that builders are single-use, or makebuild()copy everything it needs — including defensive copies of collections. - Mutable products. Adding setters to the product undoes the reason for the builder.
- Required fields as optional builder methods. Put them in the builder’s constructor or in the static
builder(...)method. - Sharing builders between threads. Builders are mutable and not thread-safe. Products can be immutable and shared; builders should be confined to one thread.
Relationship to SOLID#
- Single Responsibility: construction and validation live in the builder; the product focuses on behaviour.
- Open/Closed (GoF form): a new representation is a new concrete builder; the director does not change.
- Dependency Inversion (GoF form): the director depends on the
DocumentBuilderabstraction.
Comparison with similar patterns#
| Pattern | Difference |
|---|---|
| Factory Method / Abstract Factory | Create an object in one call, focusing on which class. Builder focuses on how one complex object is assembled, step by step. See factory patterns compared. |
| Prototype | Creates a new object by copying an existing one and adjusting it, instead of assembling it from parts. |
| Composite | Builders often assemble Composite structures, such as document trees. |
| Static factory methods | Good for a few named variants (Duration.ofSeconds). A builder suits many independent optional settings. |
Real-world uses#
java.net.http.HttpRequest.newBuilder()andHttpClient.newBuilder()(Java 11+).java.util.stream.Stream.builder()andLocale.Builder.StringBuilderassembles a string step by step, although it has no director or separate product interface.- Spring’s
UriComponentsBuilder,ResponseEntity.ok().header(...).body(...), and theHttpSecurityDSL in Spring Security.
Interview questions and answers#
What problem does the Builder pattern solve?
It replaces telescoping constructors and half-initialised JavaBeans with readable, step-by-step creation. build() validates the complete object, which can then be immutable.
What is the difference between the GoF Builder and the builder in Effective Java? The GoF Builder separates a construction process (the director) from the representation (interchangeable concrete builders). The Effective Java builder is a fluent nested class that creates one immutable type with many optional parameters. Both build objects step by step, but they solve different problems.
Is a builder thread-safe? Usually not, and it does not need to be. A builder is used by one thread to create an object. The product it creates can be immutable and therefore safe to share.
When would you use a record instead of a builder?
When all fields are required and few in number. A record gives you a canonical constructor, accessors, equals, hashCode and toString, and a compact constructor can validate the fields.
How does Builder relate to Factory Method? Factory Method decides which class to instantiate in one step. Builder controls how a complex object is assembled. A director can even use a factory method to obtain its builder.
Summary#
- Builder assembles complex objects step by step and returns them only when they are complete.
- The fluent form gives readable, validated creation of immutable objects with many optional fields.
- The GoF form separates the construction process (director) from interchangeable representations (builders).
- Use records or constructors for small objects; use a builder when the parameter list or validation becomes complex.
Related topics#
References#
- Gamma, Helm, Johnson, Vlissides. Design Patterns. Addison-Wesley, 1994. Builder, p. 97.
- Joshua Bloch. Effective Java, 3rd edition, Item 2: “Consider a builder when faced with many constructor parameters”.
java.net.http.HttpRequest.Builder, Java SE 21 API.