【設計模式】--原型深拷貝方式之序列化對象

學過設計模式的都知道原型模式有兩種形式,深拷貝和淺拷貝,其中的深拷貝又分了兩種實現方式

方式一:重寫clone方法

方式二:通過對象序列化來實現

今天就來說一下這第二種方式中的序列化。

先來看一下代碼實現:

要複製類:

public class DeepProtoType implements Serializable{
    public String name;
    public DeepCloneableTarget deepCloneableTarget;//引用類型

    public Object deepClone(){
        //創建輸出流對象
        ByteArrayOutputStream bos=null;
        ObjectOutputStream oos=null;
        //創建輸入流對象
        ByteArrayInputStream bis=null;
        ObjectInputStream ois=null;
        try{
            //序列化
            bos=new ByteArrayOutputStream();
            oos=new ObjectOutputStream(bos);
            oos.writeObject(this);//當前這個對象以對象流的方式輸出

            //反序列化
            bis=new ByteArrayInputStream(bos.toByteArray());
            ois=new ObjectInputStream(bis);
            DeepProtoType copyObj=(DeepProtoType)ois.readObject();//將流對象轉換成我定義的類對象
            return copyObj;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //關閉流
            try {
                bos.close();
                oos.close();
                bis.close();
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

客戶端:

DeepProtoType p=new DeepProtoType();

DeepPrototype pClone=(DeepProtoType)p.deepClone();

理解一下序列化,反序列化

序列化:將對象轉換爲字節序列存入磁盤

反序列化:將字節序列恢復爲對象(這個對象是一個全新的對象)

序列化實現:需要該類實現Serializable接口,該類纔可以被序列化

補充:實現Serializable接口的時候 IDEA會給出提醒,添加代碼——private static final long serialVersionUID=1L;(什麼作用讀者自己去了解一下吧)

Spring框架原型模式的使用場景:<bean id="+" class="com.calculation.add" scope="prototype"></bean>

通過bean去創建對象的一種方式是通過原型模式去創建,在此就不多介紹了,想學習的可以去看spring源碼了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章