浅克隆:
深克隆:
Java语言提供的clone()方法满足:
1.对任何的对象x,都有x.clone() != x,即克隆对象与愿对象不是同一个对象。
2.对任何的对象x,都有x.clone().getClass == x.getClass(),即克隆对象与原对象的类型一样。
3.如果对象x的equals()方法定义恰当,那么x.clone().equals(x)应该成立。
邮箱复制(浅克隆):
Attachment:
public class Attachment { public void download(){ System.out.println("Download:"); } }
Email:
public class Email implements Cloneable{ Attachment attachment = null; public Email clone(){ Object object = null; try{ object = super.clone(); }catch (CloneNotSupportedException e){ System.err.println("Not support cloneable!"); return null; } return (Email)object; } public void display(){ System.out.println("i don't know what i need to display!"); } public void setAttachment(Attachment attachment) { this.attachment = attachment; } public Attachment getAttachment() { return this.attachment; } }
Client:
public class Client { public static void main(String[] args){ Email email = new Email(); Attachment attachment = new Attachment(); email.setAttachment(attachment); Email email_1; email_1 = email.clone(); System.out.println("email 和 email_1 是否相同? " + (email == email_1)); System.out.println("email 和 email_1 的类型是否相同? " + (email.getClass() == email_1.getClass())); System.out.println("email的附件 and email_1的附件是否相同? " + (email.getAttachment() == email_1.getAttachment())); } }
Result:
email 和 email_1 是否相同? false
email 和 email_1 的类型是否相同? true
email的附件 and email_1的附件是否相同? true
邮箱复制(深克隆):通过序列化与反序列化进行深度克隆。
Attachment:
import java.io.Serializable; public class Attachment implements Serializable{ public void download(){ System.out.println("Download"); } }
Email:
import java.io.*; public class Email implements Serializable{ private Attachment attachment; public void setAttachment(Attachment attachment){ this.attachment = attachment; } public Attachment getAttachment() { return this.attachment; } public void dislay(){ System.out.println("..."); } public Email deepClone() throws IOException,ClassNotFoundException,OptionalDataException{ ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(this); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); return (Email)ois.readObject(); } }
Client:
public class Client { public static void main(String[] args){ Email email = new Email(); Email email_1 = null; Attachment attachment = new Attachment(); email.setAttachment(attachment); try { email_1 = email.deepClone(); }catch (Exception e){ System.err.println("deepClone failed!"); } System.out.println("email 和 email_1 是否相同? " + (email == email_1)); System.out.println("email 和 email_1 的类型是否相同? " + (email.getClass() == email_1.getClass())); System.out.println("email的附件 and email_1的附件是否相同? " + (email.getAttachment() == email_1.getAttachment())); } }
Result:
email 和 email_1 是否相同? false
email 和 email_1 的类型是否相同? true
email的附件 and email_1的附件是否相同? false