Appearance
建造者模式
意图
将复杂对象的构造步骤与表示分离,使同样的构建过程可以创建不同表示。适合参数多、可选参数多、构造易出错的场景。
类图
Java 示例(流式建造者)
java
public class HttpRequest {
private final String method;
private final String url;
private final String body;
private HttpRequest(Builder b) {
this.method = b.method;
this.url = b.url;
this.body = b.body;
}
public static class Builder {
private String method = "GET";
private String url;
private String body = "";
public Builder method(String m) { this.method = m; return this; }
public Builder url(String u) { this.url = u; return this; }
public Builder body(String b) { this.body = b; return this; }
public HttpRequest build() {
if (url == null || url.isEmpty()) throw new IllegalStateException("url");
return new HttpRequest(this);
}
}
}
// 使用
HttpRequest req = new HttpRequest.Builder()
.method("POST")
.url("https://api.example.com")
.body("{}")
.build();JDK 中 StringBuilder、Stream.Builder 也体现建造思想。
下一节:原型模式