码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式——原型模式

时间:2015-05-30 18:14:08      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

      当创建给定的实例的过程很昂贵或非常复杂的时候,就使用原型模式来拷贝,这种方式在创建对象要耗费很多资源的时候效率提升显著。

      实现深度克隆有两种方法,一种是实现Cloneable接口,重写clone()方法。另一种是通过序列化反序列化来获取对象的拷贝。

      看一个介绍:http://blog.csdn.net/zhengzhb/article/details/7393528

       看一个Demo:

      

public class Prototype implements Cloneable , Serializable{
	String name;
	Date date;
	
	public Prototype(String name, Date date) {
		this.name = name;
		this.date = date;
	}
	
	public Prototype() {
	}
	
	public void setDate(Date date) {
		this.date = date;
	}public void setName(String name) {
		this.name = name;
	}
    @Override
    protected Object clone() throws CloneNotSupportedException {
    	
    	return super.clone();
    }
    
    protected Object deepClone() throws CloneNotSupportedException {
    	Object obj = this.clone();
    	Prototype p = (Prototype) obj;
    	p.date = (Date) this.date.clone();
    	return obj;
    }
    
}

public class ClientOne {
	
	public static void shallowClone() throws Exception {
		Date date = new Date(12356565656L);
		Prototype p1 = new Prototype("原型对象", date);
		Prototype p2 = (Prototype) p1.clone();
		System.out.println(p1);
		System.out.println(p1.date);
		
		//p1.setDate(new Date(323232326565656L));
		date.setTime(36565656562626L);
		System.out.println(p2);
		System.out.println(p2.date);
	}
	
	public static void deepClone() throws Exception {
		Date date = new Date(12356565656L);
		Prototype p1 = new Prototype("原型对象",date);
		Prototype p2 = (Prototype) p1.deepClone();
		System.out.println(p1);
		System.out.println(p1.date);
		date.setTime(36565656562626L);
		System.out.println(p2);
		System.out.println(p2.date);
	}
	
	public static void deepCloneSerialize() throws Exception {
		Date date = new Date(12356565656L);
		Prototype p1 = new Prototype("原型对象",date);
		//通过序列化反序列化来新建一个对象
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutputStream    oos = new ObjectOutputStream(bos);
		oos.writeObject(p1);
		byte[] bytes = bos.toByteArray();
		
		ByteArrayInputStream  bis = new ByteArrayInputStream(bytes);
		ObjectInputStream	  ois = new ObjectInputStream(bis);
		Prototype p2 = (Prototype) ois.readObject();
		System.out.println(p1);
		System.out.println(p1.date);
		date.setTime(36565656562626L);
		System.out.println(p2);
		System.out.println(p2.date);
	}
	
	public static void main(String[] args) throws Exception {
		System.out.println("Shallow clone:");
		shallowClone();
		System.out.println("Deep clone:");
		deepClone();
		System.out.println("Deep clone serialize:");
		deepCloneSerialize();
		System.exit(0);
	}

}

 

设计模式——原型模式

标签:

原文地址:http://www.cnblogs.com/wxisme/p/4540634.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!