原型模式(Prototype克隆模式,拷贝模式)

通过new产生对象需要较为繁琐的数据准备或者权限检查,则使用原型模式。
克隆和new不同,new出的对象使用的是默认值,克隆的对象与原对象值相同且不会影响原对象的值。

public class Sheep impliments Cloneable{
	private String name;
	private Date birthday;
	//浅克隆
	@Override
	protected Object clone() throws CloneNotSupportedException{
		Object obj = super.clone();
		return obj;
	}
}
public class Sheep impliments Cloneable{
	private String name;
	private Date birthday;
	//深克隆
	@Override
	protected Object clone() throws CloneNotSupportedException{
		Object obj = super.clone();
		Sheep sheep = (Sheep)obj;
		sheep.birthday = (Date) this.birthday.clone();//属性也克隆 
		return obj;
	}
}

深克隆还可以采用序列化

class Sheep implements Serializable{
	private String name;
	private Date birthday;
	Sheep(String name,Date birthday){
		this.name = name;
		this.birthday = birthday;
	}
	 
	@Override
	public String toString(){
		return "Sheep{"+
			"name='"+name+'\''+
			",birthday="+birthday+
			'}';
	}
}
 
public class Main{
	public static void main(String[] args )throws Exception{
		Sheep sheep = new Sheep("lomb",newDate(111));
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(bos);
		oos.writeObject(sheep);
		ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
		ObjectInputStream ois = new ObjectInputStream(bis);
		Sheep sheep1 = (Sheep)ois.readObject();
		System.out.println(sheep);
		System.out.println(sheep1);
		System.out.println(sheep==sheep1);
	}
}

结果
Sheep{name=‘lomb’, birthday=Thu Jan 01 08:00:00 CST 1970}
Sheep{name=‘lomb’, birthday=Thu Jan 01 08:00:00 CST 1970}
false

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值