原型模式

1.元素类-组件类

public class Attachement implements Serializable{
	private Integer id;
	private BigDecimal price;
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public BigDecimal getPrice() {
		return price;
	}
	public void setPrice(BigDecimal price) {
		this.price = price;
	}
}


2.元素类-主类

public class Prototype implements Cloneable,Serializable{
	private Integer id;
	private String name;
	private Attachement at;
	
	/**
	 * 
	 * @Desc: 克隆,浅克隆
	 * @return
	 * @author:zy
	 * @version: 2016年6月1日 下午3:16:53
	 */
	public Object copy(){
		try {
			return super.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 
	 * @Desc:  深度克隆
	 * @return
	 * @author:zy
	 * @version: 2016年6月1日 下午3:27:54
	 */
	public Prototype copyDeep(){
		try {
			//将对象写入流中
			ByteArrayOutputStream bao=new ByteArrayOutputStream();
			ObjectOutputStream oos;
			oos = new ObjectOutputStream(bao);
			oos.writeObject(this);
			
			//将对象从流中取出
            ByteArrayInputStream bis=new ByteArrayInputStream(bao.toByteArray());
            ObjectInputStream ois=new ObjectInputStream(bis);
            return  (Prototype)ois.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		}
        
        return null;
	}
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Prototype other = (Prototype) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

	public Attachement getAt() {
		return at;
	}

	public void setAt(Attachement at) {
		this.at = at;
	}
	
	
}

3.测试


  实现深克隆,除了写到内存再从内存重新读取,还有一种方式,就是在引用的对象中,实现clone()方法,但是个人不是很建议,因为这样就得在每个需要深克隆的引用中实现clone()方法了。

posted @ 2016-06-28 10:30  Bug开发攻城狮  阅读(71)  评论(0编辑  收藏  举报