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

2014-11-24 08:24:30 · 作者: · 浏览: 2
Staff()));
}

public static void main(String[]args) throws IOException, ClassNotFoundException{
TheGreatestSage sage = new TheGreatestSage();
sage.change();
}
}
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.getStaff()));
}

public static void main(String[]args) throws IOException, ClassNotFoundException{
TheGreatestSage sage = new TheGreatestSage();
sage.change();
}
}

  在大圣本尊Monkey类里面,有两个克隆方法,一个是clone(),也即浅克隆;另一个是deepClone(),也即深克隆。在深克隆方法里,大圣本尊对象(一个拷贝)被序列化,然后又被反序列化。反序列化的对象就成了一个深克隆的结果。

  

[java]
public class Monkey implements Cloneable,Serializable {
//身高
private int height;
//体重
private int weight;
//生日
private Date birthDate;
//金箍棒
private GoldRingedStaff staff;
/**
* 构造函数
*/
public Monkey(){
this.birthDate = new Date();
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 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;
}

}
public class Monkey implements Cloneable,Serializable {
//身高
private int height;
//体重
private int weight;
//生日
private Date birthDate;
//金箍棒
private GoldRingedStaff staff;
/**
* 构造函数
*/
public Monkey(){
this.birthDate = new Date();
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 {