原型模式

原型模式

用一个已经创建的实例作为原型,通过克隆 获得一个新对象

使用场景

  1. 类的初始化消耗资源过多
  2. new产生的一个对象需要非常繁琐的过程
  3. 循环体中生产大量对象时,可读性下降
  4. 构造函数比较复杂

浅克隆

适用场景

克隆出来的对象和原对象中的 属性地址 一样

public class Prototype implements Cloneable {
    private int age;
    private List hobbies;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public List getHobbies() {
        return hobbies;
    }

    public void setHobbies(List hobbies) {
        this.hobbies = hobbies;
    }

    @Override
    protected Prototype clone() throws CloneNotSupportedException {
        Prototype prototype = new Prototype();
        prototype.setAge(this.age);
        prototype.setHobbies(this.hobbies);
        return prototype;
    }

}

深克隆

适用场景

克隆出一个全新的对象

public class Prototype implements Cloneable, Serializable {
    private int age;
    private List hobbies;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public List getHobbies() {
        return hobbies;
    }

    public void setHobbies(List hobbies) {
        this.hobbies = hobbies;
    }

    @Override
    protected Prototype clone() throws CloneNotSupportedException {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(this);
            oos.flush();

            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);

            Prototype prototype = (Prototype) ois.readObject();
            return prototype;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值