设计模式--原型模式

Java工程源码

类图

这里写图片描述


定义
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象


优点
- 性能优良 原型模式是在内存二进制流的拷贝,要比直接new一个对象性能好很多,特别是要在一个循环内产生大量对象时
- 逃避构造函数的约束 直接在内存中拷贝,构造函数不会执行


使用场景
- 资源优化场景 类初始化需要消耗非常多的资源时
- 性能和安全要求的场景


注意事项
- 用clone方法产生新对象时,构造函数不会被执行

抽象原型类

public abstract class Prototype implements Cloneable {

    protected ArrayList<String> arrayList = new ArrayList<>();

    public void addValue(String value) {
        this.arrayList.add(value);
    }

    public ArrayList<String> getValue() {
        return this.arrayList;
    }

    @Override
    public Prototype clone() {
        System.out.println("Prototype->clone()");
        Prototype prototypeClass = null;
        try {
            prototypeClass = (Prototype) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return prototypeClass;
    }
}

实体原型类 浅拷贝

public class ConcretePrototype1 extends Prototype {
}

实体原型类 深拷贝

public class ConcretePrototype2 extends Prototype {
    @Override
    public Prototype clone() {
        Prototype clone = super.clone();
        this.arrayList = (ArrayList<String>) this.arrayList.clone();
        return clone;
    }
}

场景类

public class Client {
    public static void main(String[] args) {
        System.out.println("<浅拷贝 拷贝对象引用>");
        Prototype prototype1 = new ConcretePrototype1();
        //原对象添加元素
        prototype1.addValue("value1");
        System.out.println("拷贝前的内容:" + prototype1.getValue());
        //生成拷贝对象
        Prototype copy1 = prototype1.clone();
        //原对象添加元素
        prototype1.addValue("value2");
        System.out.println("拷贝后的内容:" + copy1.getValue());
        // 因为拷贝的是引用地址,原对象添加元素,拷贝对象也添加元素

        System.out.println("\n<深拷贝 拷贝对象内容>");
        Prototype prototype2 = new ConcretePrototype2();
        //原对象添加元素
        prototype2.addValue("value1");
        System.out.println("拷贝前的内容:" + prototype2.getValue());
        //生成拷贝对象
        Prototype copy2 = prototype2.clone();
        //原对象添加元素
        prototype2.addValue("value2");
        System.out.println("拷贝后的内容:" + copy2.getValue());
        // 因为拷贝的是内容并且新建了引用,原对象添加元素,拷贝对象不会受到影响
    }
}

深拷贝和浅拷贝的使用视项目情况而定。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值