克隆合成工具
试图深层复制合成工具时会碰着一个问题。必需假定成员工具中的clone()要领也能依次对本身的句柄举办深层复制,以此类推。这使我们的操纵变得巨大。为了能正常实现深层复制,必需对所有类中的代码举办节制,可能至少全面把握深层复制中需要涉及的类,确保它们本身的深层复制能正确举办。
下面这个例子总结了面临一个合成工具举办深层复制时需要做哪些工作:
//: DeepCopy.java // Cloning a composed object 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(); } // Must clone handles: o.depth = (DepthReading)o.depth.clone(); o.temperature = (TemperatureReading)o.temperature.clone(); return o; // Upcasts back to Object } } public class DeepCopy { public static void main(String[] args) { OceanReading reading = new OceanReading(33.9, 100.5); // Now clone it: OceanReading r = (OceanReading)reading.clone(); } } ///:~
DepthReading和TemperatureReading很是相似;它们都只包括了根基数据范例。所以clone()要领可以或许很是简朴:挪用super.clone()并返回功效即可。留意两个类利用的clone()代码是完全一致的。
OceanReading是由DepthReading和TemperatureReading工具归并而成的。为了对其举办深层复制,clone()必需同时克隆OceanReading内的句柄。为到达这个方针,super.clone()的功效必需造型成一个OceanReading工具(以便会见depth和temperature句柄)。