建造者模式与原型模式
medium设计模式创建型建造者模式原型模式
建造者模式(Builder)
解决什么问题
当一个对象有很多可选参数时,构造函数会爆炸(telescoping constructor 问题)。建造者模式提供链式调用逐步构建复杂对象。
// 问题:参数太多,难以阅读
new User("张三", 25, "男", "北京", "13800138000", "test@email.com");
// 建造者模式:清晰明了
User user = User.builder()
.name("张三")
.age(25)
.gender("男")
.city("北京")
.phone("13800138000")
.build();
实现
public class User {
private final String name; // 必填
private final int age; // 可选
private final String city; // 可选
private User(Builder builder) {
this.name = builder.name;
this.age = builder.age;
this.city = builder.city;
}
public static class Builder {
private final String name; // 必填参数
private int age = 0;
private String city = "";
public Builder(String name) { this.name = name; }
public Builder age(int age) { this.age = age; return this; }
public Builder city(String city) { this.city = city; return this; }
public User build() { return new User(this); }
}
public static Builder builder(String name) {
return new Builder(name);
}
}
实际开发中常用 Lombok 的 @Builder 注解自动生成。
原型模式(Prototype)
解决什么问题
当创建对象的成本很高(如需要大量计算或数据库查询),通过克隆已有对象来创建新对象。
public class Prototype implements Cloneable {
private String name;
private List<String> tags;
@Override
public Prototype clone() throws CloneNotSupportedException {
Prototype copy = (Prototype) super.clone();
copy.tags = new ArrayList<>(this.tags); // 深拷贝引用类型
return copy;
}
}
浅拷贝 vs 深拷贝
| 类型 | 基本类型 | 引用类型 | 风险 |
|---|---|---|---|
| 浅拷贝 | 复制值 | 复制引用(共享同一对象) | 修改一个会影响另一个 |
| 深拷贝 | 复制值 | 创建新对象(完全独立) | 安全但开销大 |
生产高频题
建造者模式适用于什么场景?
对象有很多参数(尤其是可选参数)时,用建造者模式提供链式 API 逐步构建,比多参数构造函数更清晰,比多个 setter 方法更安全(可以创建不可变对象)。
浅拷贝和深拷贝的区别?
浅拷贝只复制引用,新旧对象共享同一个引用对象;深拷贝递归复制所有引用对象,两个对象完全独立。Java 的 clone() 默认是浅拷贝。