概要
代码实现
@Dataclass Persion implements Cloneable {private String name;private int age;private HashMap<String, String> propertis;@Overrideprotected Persion clone() throws CloneNotSupportedException {Persion persion = (Persion) super.clone();//非基本类型自定义拷贝persion.propertis = (HashMap<String, String>) this.propertis.clone();return persion;}}public class Prototype {public static void main(String[] args) throws CloneNotSupportedException {Persion persion = new Persion();persion.setAge(11);persion.setName("小明");HashMap<String, String> propertis = new HashMap<>();propertis.put("money", "20亿");propertis.put("gender", "man");persion.setPropertis(propertis);Persion persion1 = persion.clone();System.out.println(persion);System.out.println(persion1);System.out.println(persion.getPropertis() == persion1.getPropertis());}}
结果:
我是构造方法Persion(name=小明, age=11, propertis={money=20亿, gender=man})Persion(name=小明, age=11, propertis={money=20亿, gender=man})false
总结
- clone方法创建对象不会调用其构造方法。
- 被clone对象要实现Cloneable接口
- 默认super.clone只能复制基本类型,非基本类型需要自定义实现
- 原型模式可以用来快速创建复杂对象
