1. 程式人生 > >java原型設計模式

java原型設計模式

get spa zha 當前 hang throw prot super 需要

原型模式的思想:將一個對象作為原型,對其進行復制,克隆,產生一個和原對象類似的新對象。

由上可見,一個原型類,只需要實現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 }

java原型設計模式