Java 设计模式 之 克隆模式

http://www.verejava.com/?id=16999064613464

浅克隆 

package com.clone.theory;

public class TestClone
{
	public static void main(String[] args)
	{
		Prototype p=new Prototype("李阳");
		System.out.println(p.getName());
		
		Prototype p2=(Prototype)p.clone();
		System.out.println(p2.getName());
		
		p2.setName("王浩");
		System.out.println(p2.getName());
		System.out.println(p.getName());
	}
}





package com.clone.theory;

public class Person implements Cloneable
{
	private int age;

	public Person(int age)
	{
		super();
		this.age = age;
	}

	public int getAge()
	{
		return age;
	}

	public void setAge(int age)
	{
		this.age = age;
	}
	
	@Override
	protected Object clone() 
	{
		
		try
		{
			return super.clone();
		} catch (CloneNotSupportedException e)
		{
			e.printStackTrace();
		}
		return null;
	}
	
}




深克隆 


package com.clone.theory;

public class TestDeepClone
{
	public static void main(String[] args)
	{
		Prototype p=new Prototype("李阳");
		p.setPerson(new Person(20));
		System.out.println(p.getName()+","+p.getPerson().getAge());
		
		Prototype p2=(Prototype)p.clone();
		System.out.println(p2.getName()+","+p.getPerson().getAge());
		
		p2.setName("王浩");
		p2.getPerson().setAge(30);
		System.out.println(p.getName()+","+p.getPerson().getAge());
		System.out.println(p2.getName()+","+p2.getPerson().getAge());
	}
}






package com.clone.theory;

public class Prototype implements Cloneable
{
	private String name;
	private Person person;


	public Prototype(String name)
	{
		super();
		this.name = name;
	}

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}
	
	public Person getPerson()
	{
		return person;
	}

	public void setPerson(Person person)
	{
		this.person = person;
	}
	

	@Override
	protected Object clone() 
	{
		Prototype p=null;
		try
		{
			p=(Prototype)super.clone();
			p.person=(Person)person.clone();
		} catch (CloneNotSupportedException e)
		{
			e.printStackTrace();
		}
		return p;
	}
	
	
}



http://www.verejava.com/?id=16999064613464

posted @ 2018-06-28 09:16  verejava  阅读(451)  评论(0编辑  收藏  举报