Java

Builder Pattern

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
For objects with many optional parameters, a Builder beats a constructor with 12 args (or a half-initialized object you have to call setters on). Method chaining + a `build()` step that validates.
Java
Raw
public class HttpRequest {
    private final String url;
    private final String method;
    private final Map<String, String> headers;
    private final String body;
    private final int timeoutMs;

    private HttpRequest(Builder b) {
        this.url       = Objects.requireNonNull(b.url, "url");
        this.method    = b.method;
        this.headers   = Map.copyOf(b.headers);
        this.body      = b.body;
        this.timeoutMs = b.timeoutMs;
    }

    public static Builder builder() { return new Builder(); }

    public static class Builder {
        private String url;
        private String method = "GET";
        private final Map<String, String> headers = new HashMap<>();
        private String body;
        private int timeoutMs = 30_000;

        public Builder url(String url) { this.url = url; return this; }
        public Builder method(String m) { this.method = m; return this; }
        public Builder header(String k, String v) { headers.put(k, v); return this; }
        public Builder body(String body) { this.body = body; return this; }
        public Builder timeoutMs(int ms) { this.timeoutMs = ms; return this; }

        public HttpRequest build() { return new HttpRequest(this); }
    }
}

// Usage
var req = HttpRequest.builder()
    .url("https://api.example.com/users")
    .method("POST")
    .header("Content-Type", "application/json")
    .body("{\"name\":\"Alice\"}")
    .timeoutMs(10_000)
    .build();
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.