设计模式之 原型模式
原型模式以当前对象为原型(蓝本)来创建另一个新的对象,而无需知道创建的细节。
· 浅复制: 对象的基本数据类型的变量值会被重新复制和创建,而引用数据类型仍指向原对象的引用。也就是说,浅复制不复制对象的引用类型数据。
· 深复制:不论是基本数据类型还是引用数据类型,都会被重新复制和创建
(1)浅复制
public class Computer implements Cloneable{ private String cpu; private String memory; private String disk; public Computer (String cpu, String memory, String disk){ this.cpu = cpu; this.memory = memory; this.disk = disk; } public Object clone(){// 浅复制 try{ return (Computer)super.clone(); }catch(Exception e){ e.printStackTrace(); return null; } } }
(2)深复制
public class Disk implements Cloneable{ private String ssd; private String hhd; public Disk(String ssd,String hhd){ this.ssd = ssd; this.hhd = hhd; } public Object clone(){ try{ return (Disk)super.clone(); }catch(Exception e){ e.printStackTrace(); return null; } } } public class ComputerDetail implements Cloneable{ private String cpu; private String memory; private Disk disk; public ComputerDetail (String cpu, String memory, Disk disk){ this.cpu = cpu; this.memory = memory; this.disk = disk; } public Object clone(){// 深复制 try{ ComputerDetail computerDetail = (ComputerDetail)super.clone(); computerDetail.disk = (Disk)this.disk.clone(); return computerDetail; }catch(Exception e){ e.printStackTrace(); return null; } } }
(3)使用原型模型
public static void main(String[] args){ // 浅复制的 Computer computer = new Computer("8core","16G","1TB"); Computer computerClone = computer.clone(); //深复制的 Disk disk = new Disk("208G","2TB"); ComputerDetail computerDetail = new ComputerDetail("8core","16G",disk); ComputerDetail computerDetailClone = computerDetail.clone(); }