Builder Design Pattern in Java
Construct complex objects step by step with readable, flexible Java code.
What is Builder?
Builder constructs a complex object one step at a time. It is useful when a class has many optional fields and a long constructor would be difficult to read.
Simple request example
Here, the URL is required while the method and timeout have useful defaults.
public final class HttpRequest {
private final String url;
private final String method;
private final int timeout;
private HttpRequest(Builder builder) {
url = builder.url;
method = builder.method;
timeout = builder.timeout;
}
public static class Builder {
private final String url;
private String method = "GET";
private int timeout = 30;
public Builder(String url) { this.url = url; }
public Builder method(String value) {
method = value; return this;
}
public Builder timeout(int seconds) {
timeout = seconds; return this;
}
public HttpRequest build() {
return new HttpRequest(this);
}
}
}HttpRequest request = new HttpRequest.Builder(
"https://api.example.com/orders")
.method("POST")
.timeout(60)
.build();Why it reads well: each optional choice is named, and the finished object can remain immutable.
Benefits and trade-offs
Benefits
- Readable object construction.
- Handles optional values cleanly.
- Supports immutable objects.
Trade-offs
- Requires a builder class.
- May be unnecessary for tiny objects.
When should you use it?
- A class has many optional constructor parameters.
- Construction steps should be easy to understand.
- Validation is needed before creating the object.
Key takeawayBuilder makes complex construction readable and keeps the final object easy to validate and maintain.
