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

原型模式目的:当创建一个对象比较麻烦的时候,用原型模式来创建对象,提高效率。

使用:就是实现Cloneable接口和重写Object类中的clone方法(clone是本地方法,也就是c语言的方法,效率高)。

</pre><pre name="code" class="java">public class Paper implements Cloneable {
	private int id;
	private String name;
	private String sex;
	private String test1;
	private String test2;<pre name="code" class="java"><span style="white-space:pre">	</span>private Date birthday;
//浅复制,只复制对象,如果对象值变化,复制的对象也变化@Overrideprotected Object clone() throws CloneNotSupportedException {Object clone = super.clone();return clone;}}
 

在客户端调用这个方法即可。

	@Override
	protected Object clone() throws CloneNotSupportedException {
		Object clone = super.clone();
		//将克隆的对象属性也进行克隆
		Paper paper = (Paper) clone;
		paper.birthday=(Date)this.birthday.clone();
		return clone;
	}

深复制是将属性也同时克隆,这样当改变值时,克隆对象的值不变。(能克隆的是是引用类型)

也可以通过序列化和反序列化来进行深复制,也就是通过I/O流来复制。

		Paper p = new Paper();
		p.setBirthday(new Date());
		ByteArrayOutputStream bao = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(bao);
		oos.writeObject(p);
		byte[] bytes = bao.toByteArray();
		ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
		ObjectInputStream ois = new ObjectInputStream(bis);
		Paper p2 = (Paper)ois.readObject();
同样将属性和对象都克隆


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值