原型模式深浅复制

来源:互联网 发布:c语言代码图片 编辑:程序博客网 时间:2024/05/29 14:12
java.awt.Component 实现了 Serializable 接口, 所有Component的子类,包括Button、Scorollbar、TestArea、List、Container、Panel、java.applet.Applet以及所有的Applet的子类和Swing的子类都是可以串行化的。
java.lang.Throwable类实现了Serializable接口,所有的Exception和Error类均是可以串行化的。而流、所有的Reader和Writer以及其他的I/O类都是不可以串行化的。AWT和Swing、容器类、事件类都是可以串行化的。事件适配器类、图像过滤器类、AWT包中与操作系统相关的特性类都是不可以串行化的。原始类型的封装类中只有void类是可以串行化的。多数的java.lang包中的类是不可以串行化的。反射类是不可以串行化的。java.math中的类都是可以串行化的。压缩类都是不可以串行化的。
 大圣
public class TheGreatestSage {
private Monkey monkey = new Monkey();
public void change() throws Exception{
Monkey copyMonkey;
for(int i = 0;i < 2000;i++){}
copyMonkey = (Monkey)monkey.deepClone();
System.out.println("Monkey King's birth date = "+monkey.getBirthDate());
System.out.println("Copy monkey's birth date = "+copyMonkey.getBirthDate());
System.out.println("Monkey King == Copy Monkey? "+(monkey == copyMonkey));
System.out.println("Monkey King's staff == Copy Monkey's staff ?"+(monkey.getStaff() == copyMonkey.getStaff()));
}
public static void main(String[] args) throws Exception {
TheGreatestSage sage = new TheGreatestSage();
sage.change();
}
}
猴子
 
public class Monkey implements Cloneable,Serializable{
private int height;
private int weight;
private GoldRingedStaff staff;
private Date birthDate;
public Monkey() {
this.birthDate = new Date();
this.staff = new GoldRingedStaff();
}
public Object deepClone()throws Exception{
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(this);
ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
ObjectInputStream oi = new ObjectInputStream(bi);
return oi.readObject();
}
public Object clone(){
Monkey temp = null;
try{
temp = (Monkey)super.clone();
}catch(CloneNotSupportedException ex){
System.out.println("Clone failed");
}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;
}
}
金箍棒
 
public class GoldRingedStaff implements Serializable,Cloneable{
private float height = 100.0F;
private float diameter = 10.0F;
public GoldRingedStaff(){}
public void grow(){
this.diameter *= 2.0;
this.height *= 2.0;
}
public void shrink(){
this.diameter /= 2.0;
this.height /= 2;
}
public void move(){}
public float getHeight() {
return height;
}
public void setHeight(float height) {
this.height = height;
}
public float getDiameter() {
return diameter;
}
public void setDiameter(float diameter) {
this.diameter = diameter;
}
}
原创粉丝点击