模式定义

指原型实例指定创建对象的种类,并且通过拷贝这些原型创建对象新的对象

clone 方法

(直接clone 可能导致引用类型的属性指向原来的地址)除非子类里面的引用类型也实现cloneable,clone方法里面在将子类clone后覆盖原本的引用

  1. class ProtoProduct implements Cloneable{
  2. private String part1;
  3. private String part2;
  4. private String part3;
  5. private String part4;
  6. public ProtoProduct(String part1, String part2, String part3, String part4) {
  7. this.part1 = part1;
  8. this.part2 = part2;
  9. this.part3 = part3;
  10. this.part4 = part4;
  11. }
  12. @Override
  13. protected ProtoProduct clone() throws CloneNotSupportedException {
  14. return (ProtoProduct)super.clone();
  15. }
  16. public String getPart1() {
  17. return part1;
  18. }
  19. public void setPart1(String part1) {
  20. this.part1 = part1;
  21. }
  22. public String getPart2() {
  23. return part2;
  24. }
  25. public void setPart2(String part2) {
  26. this.part2 = part2;
  27. }
  28. public String getPart3() {
  29. return part3;
  30. }
  31. public void setPart3(String part3) {
  32. this.part3 = part3;
  33. }
  34. public String getPart4() {
  35. return part4;
  36. }
  37. public void setPart4(String part4) {
  38. this.part4 = part4;
  39. }
  40. }

深拷贝方式

构造函数

重载clone()方法

apache common lang 序列化

gson序列化

  1. Address address = new Address("杭州", "中国");
  2. User user = new User("大山", address);
  3. // 使用Gson序列化进行深拷贝
  4. Gson gson = new Gson();
  5. User copyUser = gson.fromJson(gson.toJson(user), User.class);
  6. // 修改源对象的值
  7. user.getAddress().setCity("深圳");
  8. // 检查两个对象的值不同
  9. assertNotSame(user.getAddress().getCity(), copyUser.getAddress().getCity());

jackson序列化

  1. Address address = new Address("杭州", "中国");
  2. User user = new User("大山", address);
  3. // 使用Jackson序列化进行深拷贝
  4. ObjectMapper objectMapper = new ObjectMapper();
  5. User copyUser = objectMapper.readValue(objectMapper.writeValueAsString(user), User.class);
  6. // 修改源对象的值
  7. user.getAddress().setCity("深圳");
  8. // 检查两个对象的值不同
  9. assertNotSame(user.getAddress().getCity(), copyUser.getAddress().getCity());