Java设计模式-----Prototype原型模式

 源自: 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());
	}
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值