Lesson 46: Design Pattern: Builder

16 Aug 2026 1 min Swarnil Singhai

Builder constructs complex objects step by step, especially useful when a class has many optional parameters that would otherwise need messy overloaded constructors.

Real-time example

An HTTP request object has method, URL, headers, and body — a Builder makes constructing one readable instead of a 6-argument constructor.

class HttpRequest {
    private final String method, url;
    private HttpRequest(Builder b) { this.method = b.method; this.url = b.url; }

    static class Builder {
        private String method = "GET", url;
        Builder method(String m) { this.method = m; return this; }
        Builder url(String u) { this.url = u; return this; }
        HttpRequest build() { return new HttpRequest(this); }
    }
}
HttpRequest req = new HttpRequest.Builder()
    .method("POST").url("/api/orders").build();

What's happening

Each builder method returns this, enabling the fluent chained-call style — readable even with many optional fields.

Builder shines exactly where telescoping constructor overloads would otherwise get out of hand.

Advertisement