快捷搜索:

软件设计模式---原型模式---邮箱复制(浅克隆和深克隆案例)

实例一:邮件复制(浅克隆) 由于邮件对象包含的内容较多(如发送者、接收者、标题、内容、日期、附件等),某系统中现需要提供一个邮件复制功能,对于已经创建好的邮件对象,可以通过复制的方式创建一个新的邮件对象,如果需要改变某部分内容,无须修改原始的邮件对象,只需要修改复制后得到的邮件对象即可。使用原型模式设计该系统。在本实例中使用浅克隆实现邮件复制,即复制邮件(Email)的同时不复制附件(Attachment)。

Attachment类:
public class Attachment
{
    public void download()
    {
    	System.out.println("下载附件");	
    }
}
客户端类:
public class Client
{
	public static void main(String a[])
	{
		Email email,copyEmail;
		
		email=new Email();
		
		copyEmail=(Email)email.clone();
		
		System.out.println("email==copyEmail?");
		System.out.println(email==copyEmail);
		
		System.out.println("email.getAttachment==copyEmail.getAttachment?"); 
		System.out.println(email.getAttachment()==copyEmail.getAttachment());			
	}
}
Email类:
public class Email implements Cloneable 
{
	private Attachment attachment=null;
	
	public Email()
	{
		this.attachment=new Attachment();
	}
	
	public Object clone()
	{
		Email clone=null;
		try
		{
			clone=(Email)super.clone();		
		}
        catch(CloneNotSupportedException e)
        {
        	System.out.println("Clone failure!");
        }
		return clone;
	}
	
	public Attachment getAttachment()
	{
		return this.attachment;
	}
	
	public void display()
	{
		System.out.println("查看邮件");	
	}
	
}

--------------------------------------------浅克隆结束-------------------------------------------------------------------------------------

实例二:邮件复制(深克隆)

import java.io.*;

public class Attachment implements Serializable
{
    public void download()
    {
    	System.out.println("下载附件");	
    }
}
import java.io.*;

public class Email implements Serializable 
{
	private Attachment attachment=null;
	
	public Email()
	{
		this.attachment=new Attachment();
	}
	
	public Object deepClone() throws IOException, ClassNotFoundException, OptionalDataException
	{
		//将对象写入流中
		ByteArrayOutputStream bao=new ByteArrayOutputStream();
		ObjectOutputStream oos=new ObjectOutputStream(bao);
		oos.writeObject(this);
		
		//将对象从流中取出
		ByteArrayInputStream bis=new ByteArrayInputStream(bao.toByteArray());
		ObjectInputStream ois=new ObjectInputStream(bis);
		return(ois.readObject());
	}
	
	public Attachment getAttachment()
	{
		return this.attachment;
	}
	
	public void display()
	{
		System.out.println("查看邮件");	
	}
	
}
客户端类:
public class Client
{
	public static void main(String a[])
	{
		Email email,copyEmail=null;
		
		email=new Email();
		
		try{
		    copyEmail=(Email)email.deepClone();	
		}
		catch(Exception e)
	    {
	   		e.printStackTrace();
	    }	
 
		
		System.out.println("email==copyEmail?");
		System.out.println(email==copyEmail);
		
		System.out.println("email.getAttachment==copyEmail.getAttachment?"); 
		System.out.println(email.getAttachment()==copyEmail.getAttachment());			
	}
}
经验分享 程序员 职场和发展