Java建造者模式
建造者模式将复杂对象的构建与表示分离,支持分步构建。
模式定义
意图:将复杂对象的构建与其表示分离,使同样的构建过程可创建不同表示。
适用场景
- 对象有多个属性,部分可选
- 构建过程需要分步完成
- 创建逻辑复杂,需要隔离
- 需要不可变对象
模式结构
产品类
Java
public class Computer {
private String cpu; // 必选
private String ram; // 必选
private String storage; // 可选
private String gpu; // 可选
private String monitor; // 可选
private Computer(Builder builder) {
this.cpu = builder.cpu;
this.ram = builder.ram;
this.storage = builder.storage;
this.gpu = builder.gpu;
this.monitor = builder.monitor;
}
// 无公开构造器,只能通过Builder创建
public static class Builder {
private String cpu;
private String ram;
private String storage;
private String gpu;
private String monitor;
public Builder(String cpu, String ram) {
this.cpu = cpu; // 必选参数
this.ram = ram;
}
public Builder storage(String storage) {
this.storage = storage;
return this;
}
public Builder gpu(String gpu) {
this.gpu = gpu;
return this;
}
public Builder monitor(String monitor) {
this.monitor = monitor;
return this;
}
public Computer build() {
return new Computer(this);
}
}
@Override
public String toString() {
return "Computer{cpu=" + cpu + ", ram=" + ram +
", storage=" + storage + ", gpu=" + gpu + "}";
}
}
链式调用
Java
Computer computer = new Computer.Builder("Intel i7", "16GB")
.storage("512GB SSD")
.gpu("NVIDIA RTX3080")
.monitor("27inch")
.build();
System.out.println(computer);
// Computer{cpu=Intel i7, ram=16GB, storage=512GB SSD, gpu=NVIDIA RTX3080}
Lombok简化
Java
import lombok.Builder;
import lombok.Getter;
@Builder
@Getter
public class Computer {
private String cpu;
private String ram;
private String storage;
private String gpu;
}
// 使用
Computer computer = Computer.builder()
.cpu("Intel i7")
.ram("16GB")
.storage("512GB")
.build();
参数校验
Java
public Computer build() {
// 校验必选参数
if (cpu == null || cpu.isEmpty()) {
throw new IllegalStateException("CPU不能为空");
}
if (ram == null || ram.isEmpty()) {
throw new IllegalStateException("内存不能为空");
}
// 校验参数组合
if (gpu != null && !"Intel".equals(cpu)) {
throw new IllegalStateException("此CPU不支持该显卡");
}
return new Computer(this);
}
StringBuilder示例
Java内置的StringBuilder就是建造者模式:
Java
StringBuilder sb = new StringBuilder()
.append("Hello")
.append(" ")
.append("World")
.append("!");
String result = sb.toString(); // "Hello World!"
建造者 vs 工厂模式
| 特性 | 建造者模式 | 工厂模式 |
|---|---|---|
| 创建方式 | 分步构建 | 一次创建 |
| 关注重点 | 构建过程 | 创建结果 |
| 参数处理 | 灵活可选 | 固定参数 |
| 对象复杂度 | 复杂对象 | 简单对象 |
| 结果类型 | 单一类型 | 多种类型 |
实际应用示例
Java
// HTTP请求构建器
public class HttpRequest {
private String url;
private String method;
private Map<String, String> headers;
private String body;
private int timeout;
private HttpRequest(Builder builder) { ... }
public static class Builder {
private String url;
private String method = "GET";
private Map<String, String> headers = new HashMap<>();
private String body;
private int timeout = 5000;
public Builder url(String url) {
this.url = url;
return this;
}
public Builder method(String method) {
this.method = method;
return this;
}
public Builder header(String key, String value) {
this.headers.put(key, value);
return this;
}
public Builder body(String body) {
this.body = body;
return this;
}
public Builder timeout(int timeout) {
this.timeout = timeout;
return this;
}
public HttpRequest build() {
if (url == null) {
throw new IllegalStateException("URL不能为空");
}
return new HttpRequest(this);
}
}
}
// 使用
HttpRequest request = HttpRequest.builder()
.url("http://example.com/api")
.method("POST")
.header("Content-Type", "application/json")
.body("{\"name\":\"张三\"}")
.timeout(10000)
.build();
注意事项
静态内部类Builder是标准实现方式
Builder返回this实现链式调用
build()方法可进行参数校验
产品构造器私有,只能通过Builder创建
适用于不可变对象的创建
要点总结
- 建造者模式分步构建复杂对象
- 式调用提供流畅的构建体验
- 可选参数灵活设置,必选参数在Builder构造器中
- build()方法可校验参数合法性
- 适用于属性多、部分可选、需要不可变对象的场景
📝 发现内容有误?点击此处直接编辑