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

2014-11-24 08:24:30 · 作者: · 浏览: 4
blic 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;
}

}
public class Monkey implements Cloneable {
//身高
private int height;
//体重
private int weight;
//生日
private Date birthDate;
//金箍棒
private GoldRingedStaff staff;
/**
* 构造函数
*/
public Monkey(){
this.birthDate = new Date();
this.staff = new GoldRingedStaff();
}
/**
* 克隆方法
*/
public Object clone(){
Monkey temp = null;
try {
temp = (Monkey) super.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
return temp;
}
}
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 {
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 {
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;
}
}

  当运行TheGreatestSage类时,首先创建大圣本尊对象,而后浅度克隆大圣本尊对象。程序在运行时打印出的信息如下:

\

 可以看出,首先,复制的大圣本尊具有和原始的大圣本尊对象一样的birthDate,而本尊对象不相等,这表明他们二者是克隆关系;其次,复制的大圣本尊所持有的金箍棒和原始的大圣本尊所持有的金箍棒为同一个对象。这表明二者所持有的金箍棒根本是一根,而不是两根。

  正如前面所述,继承自java.lang.Object类的clone()方法是浅克隆。换言之,齐天大圣的所有化身所持有的金箍棒引用全都是指向一个对象的,这与《西游记》中的描写并不一致。要纠正这一点,就需要考虑使用深克隆。

  为做到深度克隆,所有需要复制的对象都需要实现java.io.Serializable接口。

  孙大圣的源代码:

[java]
public class TheGreatestSage {
private Monkey monkey = new Monkey();

public void change() throws IOException, ClassNotFoundException{
Monkey copyMonkey = (Monkey)monkey.deepClone();
System.out.println("大圣本尊的生日是:" + monkey.getBirthDate());
System.out.println("克隆的大圣的生日是:" + monkey.getBirthDate());
System.out.println("大圣本尊跟克隆的大圣是否为同一个对象 " + (monkey == copyMonkey));
System.out.println("大圣本尊持有的金箍棒 跟 克隆的大圣持有的金箍棒是否为同一个对象? " + (monkey.getStaff() == copyMonkey.get