Java设计模式-----Prototype原型模式
2008-06-06 11:47
736 查看
源自:http://www.blogjava.net/flustar/archive/2007/12/02/prototype.html
Prototype原型模式:
通过给出一个原型对象来指明所要创建的对象类型,然后用复制这个原型对象的办法创建出更多的同类型对象。
在java的类库中已经实现了这一模式,只要你定义的类实现了Cloneable接口,用这个类所创建的对象可以做为原型对象进而克隆出更多的同类型的对象。
例子:
Prototype原型模式:
通过给出一个原型对象来指明所要创建的对象类型,然后用复制这个原型对象的办法创建出更多的同类型对象。
在java的类库中已经实现了这一模式,只要你定义的类实现了Cloneable接口,用这个类所创建的对象可以做为原型对象进而克隆出更多的同类型的对象。
例子:
public class Temp implements Serializable { private static final long serialVersionUID = -5436321229138500673L; } 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()); } }
相关文章推荐
- Java设计模式 创建模式-原型模式(Prototype)
- JAVA设计模式(05):创建型-原型模式(Prototype)
- java23种设计模式之原型模式(Prototype)
- JAVA设计模式五:--Prototype(原型模式)
- JAVA设计模式(05):创建型-原型模式(Prototype)
- Rhyme/Java 设计模式之原型模式prototype通过clone方法和反序列化实现深复制
- JAVA设计模式 — 原型模式(Prototype)
- Java设计模式之Prototype原型模式
- java23种设计模式--原型模式(prototype)
- java-设计模式-创建模式-原型模式prototype
- Java设计模式(二)Prototype(原型),Builder和Singleton(单态)
- JAVA设计模式五--Prototype(原型模式)
- Java设计模式 - Prototype(原型模式)
- 设计模式(五)----- 原型模式(Prototype)----(JAVA版)
- 浅谈JAVA设计模式之——原型模式(Prototype)
- java 设计模式之原型模式Prototype
- 浅谈Java设计模式(五)原型模式(Prototype)
- Java原型设计模式(Prototype)
- Java设计模式 原型模式(Prototype)
- Java 设计模式:原型Prototype