Builder pattern
The builder separates complex object construction from representation, replacing telescoping constructors with a readable, fluent API that validates before building.
Introduction
Builder separates the construction of a complex object from the final product. It gives callers a readable way to supply optional values, apply defaults, and validate invariants before the product is created.
TL;DR / mental model: Accumulate configuration in a temporary builder, validate the complete state at build(), and return a product whose public state matches the invariants you want to maintain.
Problem and Context
You are building an HTTP client library. Your HttpRequest class has two required fields and eight optional ones. Without a pattern, you end up with telescoping constructors.
Every new optional parameter adds another constructor shape, and supporting many combinations makes the overloads grow quickly. Callers cannot tell what 5000 or 3 mean without reading the source. You also cannot validate field combinations (like "POST requires a body") in one place because each constructor sees only its own parameter subset.
When It Helps
Builder is useful when a product has many optional settings, construction has cross-field invariants, or the finished product should be immutable. For a small, stable set of parameters, a direct constructor is usually clearer.
Participants and Structure
HttpRequest is the immutable product with final fields and no setters. HttpRequestBuilder accumulates parameters through fluent setter methods, then build() validates field combinations and constructs the final object. The caller never touches a constructor directly. Every parameter is named at the call site.
Idiomatic Example and Implementation Notes
Continue Reading with Premium
Unlock this article and every other in-depth system design guide on the platform with SDEpedia Premium.
Related Articles
The factory method replaces direct constructor calls with a method that subclasses can override to return different types. Callers depend on an abstraction, not a concrete class.
The prototype pattern creates new objects by cloning existing ones, avoiding expensive construction when you need many similar instances with minor variations.
Learn the five SOLID principles by building a real order-processing system in Java, with before and after code for every principle.