java原型设计模式

原型模式的思想:将一个对象作为原型,对其进行复制,克隆,产生一个和原对象类似的新对象。

                            由上可见,一个原型类,只需要实现cloneable接口,复写clone方法。

java中的克隆,有两种:深浅之分,具体可看http://blog.csdn.net/zhangjg_blog/article/details/18369201/

首先是浅复制:对基本类型重新开辟空间,对引用类型,依旧指向原对象所指向的

public class Prototype implements Cloneable{
     public Objec clone()throws CloneNotSupportedException{
        Prototype proto = (Prototype)super.clone();
        return proto;
    }
}

再看深复制:复制该对象,基本类型,引用类型都是重新开辟空间.

深复制需要采用流的形式读入当前对象的二进制输入,再写出二进制数据对应的对象。

关于输入输出,看http://blog.csdn.net/zsw12013/article/details/6534619

 

public class Protopyte implements Cloneable,Serializable{
    private String string;
    public Object deepClone() throws IOException,ClassNotFoundException{
//写入当前对象的二进制流 
           ByteArrayOutputStream bos = new ByteArrayOutputStream();
           ObjectOutputStream oos = new ObjectOutputStream(bos);
           oos.writeObject(this);
//读出二进制流产生的新对象
           ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteAray());
           ObjectInputStream ois = new ObjectInputStream(bis);
           return ois.readObject();
    }
         get,set
}

 

posted @ 2017-09-07 09:09  大一脚步  阅读(139)  评论(0编辑  收藏  举报