原型模式--深浅复制公用类

package basic;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public abstract class PrototypeBasic<T> implements Cloneable, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5189738655874585053L;
	
	@SuppressWarnings("unchecked")
	public T clone() throws CloneNotSupportedException {
		return (T)super.clone();
	}
	
	@SuppressWarnings("unchecked")
	public T deepClone() throws IOException, ClassNotFoundException {
		ByteArrayOutputStream bao = new ByteArrayOutputStream();
		ObjectOutputStream obs = new ObjectOutputStream(bao);
		obs.writeObject(this);
		
		ByteArrayInputStream bis = new ByteArrayInputStream(bao.toByteArray());
		ObjectInputStream ois = new ObjectInputStream(bis);
		return (T)ois.readObject();
	}

}

 

测试代码:

   

package basic;

import java.io.IOException;

public class Father extends PrototypeBasic<Father> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 860498590845379201L;
	
	private int fatherValue;
	
	private String desc;
	
	private Son son;

	public Son getSon() {
		return son;
	}

	public void setSon(Son son) {
		this.son = son;
	}

	public int getFatherValue() {
		return fatherValue;
	}

	public void setFatherValue(int fatherValue) {
		this.fatherValue = fatherValue;
	}
	
	public String getDesc() {
		return desc;
	}

	public void setDesc(String desc) {
		this.desc = desc;
	}

	public static void main(String[] args) throws CloneNotSupportedException, IOException, ClassNotFoundException {
		Father f = new Father();
		f.setFatherValue(4);
		f.setDesc("desc");
		Son son = new Son();
		son.setStr("son prototype");
		System.out.println("son's hashcode:" + son.hashCode());
		f.setSon(son);
		
		
		Father clone = f.clone();
		Father deepClone = f.deepClone();
		clone.setDesc("desc===clone");
		
		System.out.println(f.getFatherValue() + "  " +  f.getDesc() + "  " + f.getSon());
		System.out.println(clone.getFatherValue() + "  " + clone.getDesc() + "  " + clone.getSon());
		System.out.println(deepClone.getFatherValue() + "  " + deepClone.getDesc() + "  " + deepClone.getSon());
	}
	
}

 

几点说明:

 (一) 优点: 如果某个类想实现深浅复制功能,只需要和例子当中的Father类一样,继承抽象类PrototypeBasic,浅复制调用clone()方法,深复制调用deepClone()方法

 

 (二) 缺点: 需要实现复制的类继承PrototypeBasic就不能继承其他类了,以后扩展会受到影响;需要复制类的属性如果有其他类的引用,那么该引用需要实现Cloneable, Serializable接口

 

   代码只是即兴而写,只做了简单的深浅复制测试,不保证其他情况下不出现bug

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值