设计模式-原型模式(深拷贝)
浅拷贝:拷贝了对象的基本数据类型或其封装类,对于内部的数组、引用对象 依旧是采用引用的形式;
@Data public class TestEntity implements Cloneable{ private String testAid; private String testAname; private TestEntityB testEntityB; public TestEntity(){ } @Override protected TestEntity clone() { TestEntity testEntity = null; try { testEntity = (TestEntity)super.clone(); /* testEntity.testEntityB = (TestEntityB)this.getTestEntityB().clone();*/ } catch (CloneNotSupportedException e) { //异常处理 } return testEntity; }
运行结果:
虽然克隆后 a==a3为false,已经是指向不同的引用地址了, 但是其内部的对象entityB依旧指向相同的地址;这种clone方式叫浅拷贝。
深拷贝:对私有的数组,引用对象也会进行拷贝,引用不同的地址;
@Data public class TestEntity implements Cloneable{ private String testAid; private String testAname; private TestEntityB testEntityB; public TestEntity(){ } @Override protected TestEntity clone() { TestEntity testEntity = null; try { testEntity = (TestEntity)super.clone(); testEntity.testEntityB = (TestEntityB)this.getTestEntityB().clone(); //**代码 } catch (CloneNotSupportedException e) { //异常处理 } return testEntity; }
@Data public class TestEntityB implements Cloneable { private String testBId; private String testBname; @Override protected TestEntityB clone() { TestEntityB testEntityB = null; try { testEntityB = (TestEntityB)super.clone(); } catch (CloneNotSupportedException e) { } return testEntityB; }
运行结果:
注意:咱们的被引用类如果要使用clone方法必须也要实现Cloneable接口。