设计模式学习笔记(八) 原型模式

该篇主要是原型模式。

定义

用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
不通过new关键字来产生一个对象,而是通过对象复制来实现的模式就叫原型模式。

代码

public class PrototypeClass implements Cloneable {
    @Override
    public PrototypeClass clone() {
        PrototypeClass prototypeClass = null;
        try {
            prototypeClass = (PrototypeClass) super.clone();
        } catch (CloneNotSupportedException e) {
            // 异常处理
            e.printStackTrace();
        }
        return prototypeClass;
    }
}

原型模式的优点

  1. 性能优良。原型模式是在内存二进制流的拷贝,比直接new一个对象性能好很多。
  2. 逃避构造函数的约束。

浅拷贝和深拷贝

浅拷贝

Object类提供的方法clone只是拷贝本身对象,其对内部的数组、引用对象等都不拷贝,还是指向原生对象的nebula元素地址。
两个对象共享了一个私有变量,一方改了,大家都修改。
String、基本类型不会出现浅拷贝的问题。

深拷贝

以下代码进行了深拷贝,解决了浅拷贝的问题。

public class Thing implements Cloneable {

    private ArrayList<String> list = new ArrayList<>();

    @Override
    public Thing clone() {
        Thing thing = null;
        try {
            thing = (Thing) super.clone();
            this.list = (ArrayList<String>) this.list.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return thing;
    }
}

注意:要使用 clone 方法,类的成员变量上不要增加 final 关键字

猜你喜欢

转载自blog.csdn.net/dulei17816/article/details/80610445
今日推荐