概要

  • 原型模式属于创造型
  • 快速创建重复对象
  • 对象复制

    对象拷贝

  • 浅拷贝
    只复制基本类型,非基本类型需要自定义实现

  • 深拷贝
    所有对象

代码实现

  1. @Data
  2. class Persion implements Cloneable {
  3. private String name;
  4. private int age;
  5. private HashMap<String, String> propertis;
  6. @Override
  7. protected Persion clone() throws CloneNotSupportedException {
  8. Persion persion = (Persion) super.clone();
  9. //非基本类型自定义拷贝
  10. persion.propertis = (HashMap<String, String>) this.propertis.clone();
  11. return persion;
  12. }
  13. }
  14. public class Prototype {
  15. public static void main(String[] args) throws CloneNotSupportedException {
  16. Persion persion = new Persion();
  17. persion.setAge(11);
  18. persion.setName("小明");
  19. HashMap<String, String> propertis = new HashMap<>();
  20. propertis.put("money", "20亿");
  21. propertis.put("gender", "man");
  22. persion.setPropertis(propertis);
  23. Persion persion1 = persion.clone();
  24. System.out.println(persion);
  25. System.out.println(persion1);
  26. System.out.println(persion.getPropertis() == persion1.getPropertis());
  27. }
  28. }

结果:

  1. 我是构造方法
  2. Persion(name=小明, age=11, propertis={money=20亿, gender=man})
  3. Persion(name=小明, age=11, propertis={money=20亿, gender=man})
  4. false

总结

  • clone方法创建对象不会调用其构造方法。
  • 被clone对象要实现Cloneable接口
  • 默认super.clone只能复制基本类型,非基本类型需要自定义实现
  • 原型模式可以用来快速创建复杂对象