首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

合成物件深層複製:OceanReading 範例與遞迴 clone 模式

     編輯:Java 相關知識

深層複製合成物件時,必須假設成員物件的 clone() 也能正確深層複製其參考,以此類推。這要求對所有涉及類別的代碼有控制權,或至少完整掌握其深層複製正確性。

//: DeepCopy.java
class DepthReading implements Cloneable {
    private double depth;
    public DepthReading(double depth) { this.depth = depth; }
    public Object clone() {
        Object o = null;
        try { o = super.clone(); }
        catch (CloneNotSupportedException e) { e.printStackTrace(); }
        return o;
    }
}
class TemperatureReading implements Cloneable {
    private long time;
    private double temperature;
    public TemperatureReading(double temperature) {
        time = System.currentTimeMillis();
        this.temperature = temperature;
    }
    public Object clone() {
        Object o = null;
        try { o = super.clone(); }
        catch (CloneNotSupportedException e) { e.printStackTrace(); }
        return o;
    }
}
class OceanReading implements Cloneable {
    private DepthReading depth;
    private TemperatureReading temperature;
    public OceanReading(double tdata, double ddata){
        temperature = new TemperatureReading(tdata);
        depth = new DepthReading(ddata);
    }
    public Object clone() {
        OceanReading o = null;
        try { o = (OceanReading)super.clone(); }
        catch (CloneNotSupportedException e) { e.printStackTrace(); }
        // 必須手動 clone 成員參考
        o.depth = (DepthReading)o.depth.clone();
        o.temperature = (TemperatureReading)o.temperature.clone();
        return o;
    }
}
public class DeepCopy {
    public static void main(String[] args) {
        OceanReading reading = new OceanReading(33.9, 100.5);
        OceanReading r = (OceanReading)reading.clone();
    }
} ///:~

模式總結

  • DepthReading/TemperatureReading 僅含基本型別,clone() 極簡:super.clone() 即可。
  • OceanReading 合成上述兩物件。深層複製時:
    1. 呼叫 super.clone() 複製本身
    2. 將結果造型為 OceanReading 以存取成員參考
    3. 對每個成員參考顯式呼叫 clone()
    4. 回傳結果(向上造型為 Object)

此模式可遞迴應用於任意深度的物件圖。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved