《JAVA与模式》第6天―原型模式 (四)

2014-11-24 08:24:30 · 作者: · 浏览: 5
return temp;
}
}
public Object deepClone() throws IOException, ClassNotFoundException{
//将对象写到流里
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
//从流里读回来
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return ois.readObject();
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public GoldRingedStaff getStaff() {
return staff;
}
public void setStaff(GoldRingedStaff staff) {
this.staff = staff;
}

}

  可以看到,大圣本尊持有一个金箍棒(GoldRingedStaff)的实例。在大圣复制件里面,此金箍棒实例是原大圣本尊对象所持有的金箍棒对象的一个拷贝。在大圣本尊对象被序列化和反序列化时,它所持有的金箍棒对象也同时被序列化和反序列化,这使得复制的大圣的金箍棒和原大圣本尊对象所持有的金箍棒对象是两个独立的对象。

[java]
public class GoldRingedStaff implements Serializable{
private float height = 100.0f;
private float diameter = 10.0f;
/**
* 增长行为,每次调用长度和半径增加一倍
*/
public void grow(){
this.diameter *= 2;
this.height *= 2;
}
/**
* 缩小行为,每次调用长度和半径减少一半
*/
public void shrink(){
this.diameter /= 2;
this.height /= 2;
}
}
public class GoldRingedStaff implements Serializable{
private float height = 100.0f;
private float diameter = 10.0f;
/**
* 增长行为,每次调用长度和半径增加一倍
*/
public void grow(){
this.diameter *= 2;
this.height *= 2;
}
/**
* 缩小行为,每次调用长度和半径减少一半
*/
public void shrink(){
this.diameter /= 2;
this.height /= 2;
}
}

\

  从运行的结果可以看出,大圣的金箍棒和他的身外之身的金箍棒是不同的对象。这是因为使用了深克隆,从而把大圣本尊所引用的对象也都复制了一遍,其中也包括金箍棒。

作者:m13666368773