`

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

阅读更多
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

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics