標籤: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原型設計模式