javaintermediate

Builder Pattern — Fluent Object Construction

Implement the Builder pattern for complex objects with validation, immutability, and method chaining.

java
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.