测试代码
/** * @description: 原型模式测试 * @author: lmc * @create: 2019-05-29 21:46 **/ public class PrototypeClientTest { public static void main(String[] args) throws CloneNotSupportedException { Invoice invoice=new Invoice(); invoice.setColor("bule"); invoice.setTicketNo(1); invoice.setEffective(false); invoice.setCompanySeal(new Seal()); //测试浅克隆 //Invoice invoiceClone = (Invoice) invoice.getShallowCloneInstance(); // Invoice invoiceClone = (Invoice) invoice.getDeepCloneInstance(invoice); /** * 验证对象是否同一个。 */ System.out.println("invoice_"+invoice.hashCode()); System.out.println("Clone_invoice_"+invoiceClone.hashCode()); System.out.println("验证对象_"+(invoice==invoiceClone)); /** * 验证基本数据类型是否相等。 */ System.out.println("getTicketNo_"+invoice.getTicketNo()); System.out.println("Clone_getTicketNo_"+invoiceClone.getTicketNo()); System.out.println("验证基本数据类型_"+(invoice.getTicketNo()==invoiceClone.getTicketNo())); /** * 验证引用数据类型是否相等 */ System.out.println("getColor_"+invoice.getColor().hashCode()); System.out.println("Clone_getColor_"+invoiceClone.getColor().hashCode()); System.out.println("验证引用数据类型_"+(invoiceClone.getColor() == invoice.getColor())); System.out.println("getCompanySeal_"+invoice.getCompanySeal().hashCode()); System.out.println("Clone_getCompanySeal_"+invoiceClone.getCompanySeal().hashCode()); System.out.println("验证引用数据类型_"+(invoice.getCompanySeal() == invoiceClone.getCompanySeal())); System.out.println("____________________________________________________________"); /** * 验证基本数据类型修改 */ invoice.setTicketNo(2); System.out.println("验证基本数据类型修改"+invoice); System.out.println("验证基本数据类型修改"+invoiceClone); /** * 验证基本数据类型保包装类 */ invoice.setEffective(true); System.out.println("验证基本数据类型包装类"+invoice); System.out.println("验证基本数据类型包装类"+invoiceClone); /** * 验证引用数据类型 */ invoice.getCompanySeal().setName("验证引用数据类型"); System.out.println("验证引用数据类型"+invoice); System.out.println("验证引用数据类型"+invoiceClone); } }测试深克隆结果
深克隆的对象和原对象 是两个独立的对象,虽然他们的内容相同,但是他们没有任何关联。
测试浅克隆结果