Java建造者模式实现案例
建造者模式(Builder Pattern)是一种创建型设计模式,用于将复杂对象的构建过程与其表示分离,以下是几种常见的实现方式:

经典建造者模式(适用于复杂对象构建)
// 产品类
public class Computer {
private String cpu;
private String ram;
private String storage;
private String gpu;
private boolean hasBluetooth;
// 私有构造方法
private Computer(Builder builder) {
this.cpu = builder.cpu;
this.ram = builder.ram;
this.storage = builder.storage;
this.gpu = builder.gpu;
this.hasBluetooth = builder.hasBluetooth;
}
// 静态内部建造者类
public static class Builder {
private String cpu;
private String ram;
private String storage;
private String gpu;
private boolean hasBluetooth;
public Builder setCpu(String cpu) {
this.cpu = cpu;
return this;
}
public Builder setRam(String ram) {
this.ram = ram;
return this;
}
public Builder setStorage(String storage) {
this.storage = storage;
return this;
}
public Builder setGpu(String gpu) {
this.gpu = gpu;
return this;
}
public Builder setHasBluetooth(boolean hasBluetooth) {
this.hasBluetooth = hasBluetooth;
return this;
}
public Computer build() {
// 可以在构建前进行参数校验
if (cpu == null || ram == null || storage == null) {
throw new IllegalStateException("CPU、RAM和存储是必填项");
}
return new Computer(this);
}
}
// getter方法
@Override
public String toString() {
return "Computer{" +
"cpu='" + cpu + '\'' +
", ram='" + ram + '\'' +
", storage='" + storage + '\'' +
", gpu='" + gpu + '\'' +
", hasBluetooth=" + hasBluetooth +
'}';
}
}
使用Lombok的@Builder注解(简化版)
import lombok.Builder;
import lombok.ToString;
@Builder
@ToString
public class User {
private String username;
private String email;
private int age;
private String phone;
private String address;
// 可以自定义构建逻辑
public static class UserBuilder {
public User build() {
// 可以添加自定义验证逻辑
if (username == null || username.isEmpty()) {
throw new IllegalArgumentException("用户名不能为空");
}
return new User(username, email, age, phone, address);
}
}
}
使用建议
适用场景:
- 对象有大量可选参数
- 参数之间存在依赖关系或验证逻辑
- 希望创建不可变对象
优点:
- 参数名清晰,减少错误
- 支持链式调用
- 可以在构建时进行参数校验
- 对象创建过程与表示分离
使用示例:
// 传统方式
Computer computer = new Computer.Builder()
.setCpu("Intel i7")
.setRam("16GB")
.setStorage("512GB SSD")
.setGpu("RTX 3060")
.setHasBluetooth(true)
.build();
// Lombok方式
User user = User.builder()
.username("张三")
.email("zhangsan@example.com")
.age(25)
.phone("13800138000")
.build();
选择哪种方式取决于你的项目需求和团队规范。