创建模式之原型模式浅克隆

 

package com.djk.design.factory.clone;

public class ShallowCloen implements Cloneable
{
	private String name;

	private int age;
	
	private Teacher teacher;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public Teacher getTeacher() {
		return teacher;
	}

	public void setTeacher(Teacher teacher) {
		this.teacher = teacher;
	}
	
	@Override
	public Object clone() throws CloneNotSupportedException 
	{
		return super.clone();
	}

	@Override
	public String toString()
	{
		return "ShallowCloen [age=" + age + ", name=" + name + ", teacher="
				+ teacher + "]";
	}
}

package com.djk.design.factory.clone;

public class Teacher 
{
	private String terchearName;
	
	private int terchearAge;

	public String getTerchearName() {
		return terchearName;
	}

	public void setTerchearName(String terchearName) {
		this.terchearName = terchearName;
	}

	public int getTerchearAge() {
		return terchearAge;
	}

	public void setTerchearAge(int terchearAge) {
		this.terchearAge = terchearAge;
	}

	@Override
	public String toString() 
	{
		return "Teacher [terchearAge=" + terchearAge + ", terchearName="
				+ terchearName + "]";
	}
	
	
}
package com.djk.design.factory.clone;

public class Client 
{	
	public static void main(String[] args) throws CloneNotSupportedException 
	{
		Teacher teacher = new Teacher();
		teacher.setTerchearAge(32);
		teacher.setTerchearName("djk");
		
		ShallowCloen shallowCloen = new ShallowCloen();
		shallowCloen.setAge(24);
		shallowCloen.setName("test");
		shallowCloen.setTeacher(teacher);
		
		System.out.println(shallowCloen);
		
		ShallowCloen cloneShallow = (ShallowCloen) shallowCloen.clone();
		
		System.out.println(cloneShallow);
		
		cloneShallow.setAge(40);
		System.out.println(cloneShallow);
		System.out.println(shallowCloen);
		
		cloneShallow.getTeacher().setTerchearAge(45);
		System.out.println(cloneShallow);
		System.out.println(shallowCloen);
	}
}

原型模式就是对对象的克隆,克隆分浅克隆和深克隆,上面介绍的是浅克隆,由上面的代码可以知道浅克隆对象的时候,当浅克隆对象里面有另一个对象的引用,则克隆出来的对象改变克隆对象里面的引用的时候会影响到原来的对象。所以当浅克隆对象里面有对另一个对象的引用的时候,克隆的是这个对象在java栈里面的值而没有克隆引用对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值