GOF创建型模式:原型模式

浅克隆:

import com.sun.jndi.cosnaming.IiopUrl;

class Address{

        }

public class Customer implements Cloneable {
    private Address address =null;
    public Customer(){
        this.address=new Address();
    }

    public Object clone(){
        Object obj =null;
        try{
            obj=super.clone();
        }catch (Exception e){
            System.out.println("clone failure");
        }
        return obj;
    }
}

深克隆:
class customer implements Serializable{
    private Address address =null;
    public customer(){
        this.address= new Address();
    }
    public Object deepClone() throws Exception{
        ByteArrayOutputStream bao =new ByteArrayOutputStream();
        ObjectOutputStream os =new ObjectOutputStream(bao);
        os.writeObject(this);
        ByteArrayInputStream bis =new ByteArrayInputStream(bao.toByteArray());
        ObjectInputStream ois =new ObjectInputStream(bis);
        return (ois.readObject());
    }

}

实验结果分析
浅克隆中,Object类充当抽象原型类,Customer类充当具体原型类,浅克隆只复制容器对象,不复制成员对象。
深克隆,Customer和Address实现了Serializable接口,深克隆既要复制容器对象,又要复制成员对象。

全部评论

相关推荐

鼠鼠第一次实习,啥也不懂一直是自己一个人吃的饭,不会做工作老是被嫌弃,大人的世界是这样的吗?
我是星星我会发亮:好的mt有两种,一种愿意教你的,一种几乎什么活都不给你派让你很闲允许你做自己事情的
实习吐槽大会
点赞 评论 收藏
分享
06-23 11:28
门头沟学院 Java
牛客91966197...:也有可能是点拒绝的时候自动弹的话术
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务