Builder Pattern — Fluent Object Construction
Implement the Builder pattern for complex objects with validation, immutability, and method chaining.
import java.util.*;
public class HttpRequest {
private final String method;
private final String url;
private final Map<String, String> headers;
private final String body;
private final int timeoutMs;
private HttpRequest(Builder builder) {
this.method = builder.method;
this.url = builder.url;
this.headers = Collections.unmodifiableMap(builder.headers);
this.body = builder.body;
this.timeoutMs = builder.timeoutMs;
}
// Getters
public String method() { return method; }
public String url() { return url; }
public Map<String, String> headers() { return headers; }
public String body() { return body; }
public int timeoutMs() { return timeoutMs; }
public static Builder builder(String method, String url) {
return new Builder(method, url);
}
public static class Builder {
private final String method;
private final String url;
private final Map<String, String> headers = new HashMap<>();
private String body;
private int timeoutMs = 30_000;
private Builder(String method, String url) {
this.method = Objects.requireNonNull(method);
this.url = Objects.requireNonNull(url);
}
public Builder header(String key, String value) {
headers.put(key, value);
return this;
}
public Builder body(String body) {
this.body = body;
return this;
}
public Builder timeout(int ms) {
if (ms <= 0) throw new IllegalArgumentException("Timeout must be positive");
this.timeoutMs = ms;
return this;
}
public HttpRequest build() {
if ("POST".equals(method) && body == null) {
throw new IllegalStateException("POST requires a body");
}
return new HttpRequest(this);
}
}
public static void main(String[] args) {
HttpRequest req = HttpRequest.builder("POST", "https://api.example.com/users")
.header("Content-Type", "application/json")
.header("Authorization", "Bearer token123")
.body("{\"name\": \"Alice\"}")
.timeout(5000)
.build();
System.out.println(req.method() + " " + req.url());
}
}Use Cases
- Constructing complex objects with many optional parameters
- Fluent API design for configuration objects
- Immutable object creation with validation
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
Factory Method Pattern with Registry
Implement the Factory pattern using a registry map for extensible object creation without switch statements.
Best for: Extensible object creation in plugin architectures
Type-Safe Step Builder Pattern
Enforce required fields at compile time with a step builder: each step returns the next interface.
Best for: Enforcing required fields at compile time
Singleton Pattern — Thread-Safe Approaches
Implement thread-safe singletons in Java: enum, holder class, double-checked locking, and eager init.
Best for: Application-wide configuration managers
Strategy Pattern with Lambdas
Implement the Strategy pattern using interfaces and Java lambdas for flexible algorithm selection.
Best for: Swappable pricing or discount algorithms