设计模式之(三)--原型模式(prototype)

    技术2022-05-19  22

    Prototype模式的意图是: 通过给出一个原型对象来指明所要创建的对象类型,然后用复制这个原型对象的办法创建出更多的同类型对象。 在java的类库中已经实现了这一模式,只要你定义的类实现了Cloneable接口,用这个类所创建的对象可以做为原型对象进而克隆出更多的同类型的对象。代码如下:

     

     public class Temp implements Serializable{ private static final long serialVersionUID = 2268148613723588359L; } import java.io.*; public class Prototype implements Cloneable, Serializable { private static final long serialVersionUID = -840134430739337126L; private String str; private Temp temp; public Object clone() throws CloneNotSupportedException { // 浅克隆 Prototype prototype = (Prototype) super.clone(); return prototype; } public Object deepClone() throws IOException, ClassNotFoundException { // 深克隆 ByteArrayOutputStream bo = new ByteArrayOutputStream(); ObjectOutputStream oo = new ObjectOutputStream(bo); oo.writeObject(this); ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray()); ObjectInputStream oi = new ObjectInputStream(bi); return oi.readObject(); } public String getStr() { return str; } public void setStr(String str) { this.str = str; } public Temp getTemp() { return temp; } public void setTemp(Temp temp) { this.temp = temp; } } public class Client { public static void main(String[] args) throws CloneNotSupportedException, ClassNotFoundException, IOException { Prototype pt = new Prototype(); Temp temp = new Temp(); pt.setTemp(temp); pt.setStr("Hello World"); System.out.println("使用浅克隆方法进行创建对象"); Prototype pt1 = (Prototype) pt.clone(); System.out.println("============================="); System.out.println("比较pt和pt1的str的值:"); System.out.println(pt.getStr()); System.out.println(pt1.getStr()); System.out.println("修改pt1对象中str的值后,比较pt和pt1的str的值:"); pt1.setStr("你好,世界"); System.out.println(pt.getStr()); System.out.println(pt1.getStr()); System.out.println("============================"); System.out.println("比较pt和pt1中temp对象的值"); System.out.println(pt.getTemp()); System.out.println(pt1.getTemp()); System.out.println("使用深克隆方法进行创建对象"); System.out.println("============================"); pt1 = (Prototype) pt.deepClone(); System.out.println(pt.getTemp()); System.out.println(pt1.getTemp()); } }

    输出结果:使用浅克隆方法进行创建对象=============================比较pt和pt1的str的值:Hello WorldHello World修改pt1对象中str的值后,比较pt和pt1的str的值:Hello World你好,世界============================比较pt和pt1中temp对象的值com.pattern.build.prototype.Temp@d9f9c3com.pattern.build.prototype.Temp@d9f9c3使用深克隆方法进行创建对象============================com.pattern.build.prototype.Temp@d9f9c3com.pattern.build.prototype.Temp@530daa


    最新回复(0)