java原型設計模式

來源:互聯網
上載者:User

標籤:prototype   blog   exception   nbsp   span   string   input   二進位   設計   

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

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.