JavaOmnibus
GoF Builder
GoF pattern • Creational
GoFCreationalJava example

Builder solves a specific structural problem in the design.

Assemble complex objects step by step with readable construction logic.

Pattern overview

GoF pattern

Assemble complex objects step by step with readable construction logic.

Intent

Separate the construction of a complex object from its representation so the same process can create different results or optional combinations.

Problem

Constructors or factories become unreadable when an object has many optional settings, validation steps, or staged assembly rules.

Solution

Move object assembly into a builder that captures intent one step at a time before producing the final immutable object.

Fit and tradeoffs

FamilyGoF
CategoryCreational
Best used when
  • When construction requires many optional parameters.
  • When step order or validation matters.
  • When immutability is desired but constructors would be noisy.
Tradeoffs
  • Adds an extra type and API surface.
  • Can be overkill for simple data holders.

Java example

This example is intentionally compact so the pattern shape stays easy to see.

public final class HttpRequest {
    private final String method;
    private final String path;
    private final Map<String, String> headers;

    private HttpRequest(Builder builder) {
        this.method = builder.method;
        this.path = builder.path;
        this.headers = Map.copyOf(builder.headers);
    }

    public static class Builder {
        private String method = "GET";
        private String path = "/";
        private final Map<String, String> headers = new LinkedHashMap<>();

        public Builder method(String method) { this.method = method; return this; }
        public Builder path(String path) { this.path = path; return this; }
        public Builder header(String key, String value) { headers.put(key, value); return this; }
        public HttpRequest build() { return new HttpRequest(this); }
    }
}

Related pages

Keep exploring