| 意图 | 以克隆代替从头构造 |
|---|---|
| 关键 | 浅拷贝 vs 深拷贝 |
| 接口 | Java Cloneable / copy 构造器 / 序列化 |
拷贝构造器(推荐形态)
拷贝构造器(推荐形态)
class Config {
final List<String> hosts;
Config(Config other) {
this.hosts = List.copyOf(other.hosts);
}
}通过克隆已有实例创建新对象:配置模板、成本高昂的初始化对象适合此模式;注意浅克隆与深克隆的区分,成员含引用类型时要显式深拷贝策略。
| 意图 | 以克隆代替从头构造 |
|---|---|
| 关键 | 浅拷贝 vs 深拷贝 |
| 接口 | Java Cloneable / copy 构造器 / 序列化 |
class Config {
final List<String> hosts;
Config(Config other) {
this.hosts = List.copyOf(other.hosts);
}
}