源自:
http://www.blogjava.net/flustar/archive/2007/12/02/prototype.html
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());
}
}