扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
package prototype;

public interface Prototype ...{
public void printPart();
Object flatClone();
Object deepClone() throws Exception;
}

package prototype;
import java.io.*;

public class ConcretePrototype implements Prototype , Serializable...{
private Part part;

public ConcretePrototype() ...{
part = new Part();
}

public void printPart() ...{
System.out.println(part);
}


public Object flatClone() ...{
ConcretePrototype cp = new ConcretePrototype();
cp.part = this.part;
return cp;
}

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());
}

class Part implements Serializable ...{
}
}

package prototype;

public class Client ...{

public static void main(String[] args) throws Exception ...{
ConcretePrototype originate, cloned, deepCloned;
originate = new ConcretePrototype();
Thread.sleep(2000);
cloned = (ConcretePrototype)originate.flatClone();
deepCloned = (ConcretePrototype)originate.deepClone();
System.out.println(originate);
System.out.println(cloned);
System.out.println(deepCloned);
originate.printPart();
cloned.printPart();
deepCloned.printPart();
}
}
可以看出,打印的前三行各不相同,这说明通过浅复制和深复制,所得到的对象都是与原对象不同的;打印的后三行中有两行相同,这说明,在浅复制时,成员对象的实体没有被复制,只是复制了其句柄,而深复制时,成员对象的实体也被复制了。
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。