建造者模式的核心价值在于让复杂对象的创建过程可控、可读、可校验;它适用于多字段、有依赖或需统一验证的场景,通过私有构造+静态内部builder类、链式调用及build()终审校验实现。

建造者模式不是为“炫技”而存在,它的核心价值在于:让复杂对象的创建过程可控、可读、可校验。当你面对一个含多个必填/可选字段、字段间有依赖关系、或需在构建完成前统一验证的对象时,它就是最自然的选择。
明确哪些变量必须设置、哪些可选,并分离必填与可选逻辑
先不急着写 Builder 类,而是站在使用者角度想清楚:这个对象要能用,最少得有哪些信息?哪些字段之间不能共存或必须成对出现?比如一个 HttpRequest 对象:
- URL 和 HTTP 方法(GET/POST)是必填项——缺一不可
- 超时时间若未设,默认 5 秒;但若设了连接超时,读取超时也建议设(非强制,但可预警)
- 请求体(body)和请求头(headers)可为空,但如果方法是 POST 且 body 为空,应提示可能遗漏
这些规则不是写在文档里,而是直接嵌入 Builder 的 build() 方法中,确保对象一旦生成,就天然满足业务约束。
用静态内部 Builder 类封装构造细节,禁止外部直接 new
把目标类的构造函数设为 private,只暴露一个静态内部 Builder 类。Builder 自身用链式调用(return this;)提升可读性,并把字段校验收口到 build() 中:
public class HttpRequest {
private final String url;
private final String method;
private final int connectTimeout;
private final int readTimeout;
private final String body;
private final Map<string string> headers;
private HttpRequest(Builder builder) {
this.url = Objects.requireNonNull(builder.url, "URL must not be null");
this.method = Objects.requireNonNull(builder.method, "Method must not be null");
this.connectTimeout = builder.connectTimeout > 0 ? builder.connectTimeout : 5000;
this.readTimeout = builder.readTimeout > 0 ? builder.readTimeout : 5000;
this.body = builder.body;
this.headers = Collections.unmodifiableMap(
Optional.ofNullable(builder.headers).orElse(Map.of())
);
}
public static class Builder {
private String url;
private String method;
private int connectTimeout = 0;
private int readTimeout = 0;
private String body;
private Map<string string> headers;
public Builder url(String url) { this.url = url; return this; }
public Builder method(String method) { this.method = method; return this; }
public Builder timeout(int connect, int read) {
this.connectTimeout = connect; this.readTimeout = read; return this;
}
public Builder body(String body) { this.body = body; return this; }
public Builder header(String key, String value) {
if (this.headers == null) this.headers = new HashMap();
this.headers.put(key, value);
return this;
}
public HttpRequest build() {
// ✅ 统一校验入口
if (url == null || method == null) {
throw new IllegalStateException("URL and method are required");
}
if ("POST".equalsIgnoreCase(method) && body == null && (headers == null || !headers.containsKey("Content-Type"))) {
throw new IllegalStateException("POST request missing body or Content-Type header");
}
return new HttpRequest(this);
}
}
}</string></string>
在 build() 中做最终合法性验证,而不是 setter 里分散处理
避免在每个 setter(如 timeout())里抛异常——那会破坏链式调用,也让用户无法“先配好再检查”。Builder 应该允许自由设置,只在 build() 这一刻做终审:
- 检查必填字段是否为空
- 检查字段组合是否合理(如:设置了队列长度,就不强制要求最大线程数;反之则必须)
- 检查数值范围(如超时不能为负)、格式(如邮箱字段是否符合正则)
- 校验通过才 new 实例,否则明确报错,错误信息带上下文(如“缺少 method,无法发送请求”)
配合 Lombok 简化样板代码,但不牺牲校验能力
如果你用 Lombok,可以用 @Builder 自动生成 Builder,但注意:它默认不做任何校验。你需要手动补上 build() 方法并覆盖验证逻辑:
@Builder
public class Notification {
private final String sender;
private final List<string> receivers;
private final String content;
private final String type; // email/sms/inapp
// 手动定义 build 方法,替代 Lombok 自动生成的
public static NotificationBuilder builder() {
return new NotificationBuilder();
}
public static class NotificationBuilder {
private String sender;
private List<string> receivers;
private String content;
private String type;
public NotificationBuilder sender(String sender) { this.sender = sender; return this; }
public NotificationBuilder receivers(List<string> r) { this.receivers = r; return this; }
public NotificationBuilder content(String c) { this.content = c; return this; }
public NotificationBuilder type(String t) { this.type = t; return this; }
public Notification build() {
if (sender == null || receivers == null || receivers.isEmpty() || content == null || type == null) {
throw new IllegalArgumentException("sender, receivers, content, type must all be set");
}
if (!List.of("email", "sms", "inapp").contains(type)) {
throw new IllegalArgumentException("type must be one of: email, sms, inapp");
}
return new Notification(this);
}
}
}</string></string></string>
这样既享受了链式调用的简洁,又保留了强校验能力。










