模式定义
指原型实例指定创建对象的种类,并且通过拷贝这些原型创建对象新的对象
clone 方法
(直接clone 可能导致引用类型的属性指向原来的地址)除非子类里面的引用类型也实现cloneable,clone方法里面在将子类clone后覆盖原本的引用
class ProtoProduct implements Cloneable{
private String part1;
private String part2;
private String part3;
private String part4;
public ProtoProduct(String part1, String part2, String part3, String part4) {
this.part1 = part1;
this.part2 = part2;
this.part3 = part3;
this.part4 = part4;
}
@Override
protected ProtoProduct clone() throws CloneNotSupportedException {
return (ProtoProduct)super.clone();
}
public String getPart1() {
return part1;
}
public void setPart1(String part1) {
this.part1 = part1;
}
public String getPart2() {
return part2;
}
public void setPart2(String part2) {
this.part2 = part2;
}
public String getPart3() {
return part3;
}
public void setPart3(String part3) {
this.part3 = part3;
}
public String getPart4() {
return part4;
}
public void setPart4(String part4) {
this.part4 = part4;
}
}
深拷贝方式
构造函数
重载clone()方法
apache common lang 序列化
gson序列化
Address address = new Address("杭州", "中国");
User user = new User("大山", address);
// 使用Gson序列化进行深拷贝
Gson gson = new Gson();
User copyUser = gson.fromJson(gson.toJson(user), User.class);
// 修改源对象的值
user.getAddress().setCity("深圳");
// 检查两个对象的值不同
assertNotSame(user.getAddress().getCity(), copyUser.getAddress().getCity());
jackson序列化
Address address = new Address("杭州", "中国");
User user = new User("大山", address);
// 使用Jackson序列化进行深拷贝
ObjectMapper objectMapper = new ObjectMapper();
User copyUser = objectMapper.readValue(objectMapper.writeValueAsString(user), User.class);
// 修改源对象的值
user.getAddress().setCity("深圳");
// 检查两个对象的值不同
assertNotSame(user.getAddress().getCity(), copyUser.getAddress().getCity());