顧客:「給我幾個快遞。」快遞員:「寄往什麼地方?寄給...?」顧客:「和上次差很少同樣,只是郵寄給另一個地址,這裏是郵寄地址...「把郵寄地址的紙條給快遞員。快遞員:「好。」
public class PackageInfo implements Cloneable { public PackageInfo clone() { try { return (PackageInfo) super .clone(); } catch (CloneNotSupportedException e) { System. out .println( "Cloning not allowed." ); return null ; } } // 靜態工廠方法:根據原型建立一份副本 public static PackageInfo clonePackage(String userName) { // 根據 userName加載一條用戶之前的數據做爲原型數據(數據庫或其它保存的數據) PackageInfo prototype = loadPackageInfo (userName); // 再在內存中克隆這條數據 prototype = prototypr .clone(); // 初始化數據 id(主鍵) prototype. setId ( null ); // 返回數據 return prototype; } }
//DeepCopyBean實現了 java.io.Serializable接口 public class DeepCopyBean implements Serializable { // 原始類型屬性 private int primitiveField ; // 對象屬性 private String objectField ; // 首先序列化本身到流中,而後從流中反序列化,獲得得對象即是一個新的深拷貝 public DeepCopyBean deepCopy() { try { ByteArrayOutputStream buf = new ByteArrayOutputStream(); ObjectOutputStream o = new ObjectOutputStream(buf); o.writeObject( this ); ObjectInputStream in = new ObjectInputStream( new ByteArrayInputStream(buf.toByteArray())); return (DeepCopyBean) in.readObject(); } catch (Exception e) { e.printStackTrace(); } return null ; } // 屬性 get、set 方法略... // 測試demo public static void main(String[] args) { DeepCopyBean originalBean = new DeepCopyBean(); // 建立兩個 String對象,其中一個在 JVM的字符串池(String pool)裏,屬性引用指向另一個在堆裏的對象 originalBean.setObjectField( new String( "guilin" )); originalBean.setPrimitiveField(50); // 深拷貝 DeepCopyBean newBean = originalBean.deepCopy(); // 原始類型屬性值比較:true System. out .println( "primitiveField ==:" + (originalBean.getPrimitiveField() == newBean .getPrimitiveField())); // 對象屬性值比較:false(證實未指向相同的地址) System. out .println( "objectField ==:" + (originalBean.getObjectField() == newBean.getObjectField())); // 對象屬性 equals 比較:true System. out .println( "objectField equal:" + (originalBean.getObjectField().equals(newBean .getObjectField()))); } }