博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
设计模式之原型模式
阅读量:3909 次
发布时间:2019-05-23

本文共 6500 字,大约阅读时间需要 21 分钟。

1.4 原型模式

代码地址:

文章目录

(1)概念

原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。

这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。例如,一个对象需要在一个高代价的数据库操作之后被创建。我们可以缓存该对象,在下一个请求时返回它的克隆,在需要的时候更新数据库,以此来减少数据库调用。

(2)适用场景

何时使用:

1、当一个系统应该独立于它的产品创建,构成和表示时。

2、当要实例化的类是在运行时刻指定时,例如,通过动态装载。

3、为了避免创建一个与产品类层次平行的工厂类层次时。

4、当一个类的实例只能有几个不同状态组合中的一种时。建立相应数目的原型并克隆它们可能比每次用合适的状态手工实例化该类更方便一些。

**如何解决:**利用已有的一个原型对象,快速地生成和原型对象一样的实例。

关键代码:

1、实现克隆操作,在 JAVA 继承 Cloneable,重写 clone(),在 .NET 中可以使用 Object 类的 MemberwiseClone() 方法来实现对象的浅拷贝或通过序列化的方式来实现深拷贝。

2、原型模式同样用于隔离类对象的使用者和具体类型(易变类)之间的耦合关系,它同样要求这些"易变类"拥有稳定的接口。

应用实例: 1、细胞分裂。 2、JAVA 中的 Object clone() 方法。

(3)代码示例

创建一个实现了 Cloneable 接口的抽象类。

package com.alibaba.design.prototypepattern;/** * @author zhouyanxiang * @create 2020-07-2020/7/31-15:31 */public abstract class Shape implements Cloneable {    private String id;    protected String type;    abstract void draw();    public String getType(){        return type;    }    public String getId() {        return id;    }    public void setId(String id) {        this.id = id;    }    public Object clone() {        Object clone = null;        try {            clone = super.clone();        } catch (CloneNotSupportedException e) {            e.printStackTrace();        }        return clone;    }}
  • Circle.java
package com.alibaba.design.prototypepattern;/** * @author zhouyanxiang * @create 2020-07-2020/7/31-15:34 */public class Circle extends Shape {    public Circle(){        type = "Circle";    }    @Override    public void draw() {        System.out.println("Inside Circle::draw() method.");    }}
  • Rectangle.java
package com.alibaba.design.prototypepattern;/** * @author zhouyanxiang * @create 2020-07-2020/7/31-15:32 */public class Rectangle extends Shape {    public Rectangle(){        type = "Rectangle";    }    @Override    void draw() {        System.out.println("Inside Rectangle::draw() method.");    }}
  • Square.java
package com.alibaba.design.prototypepattern;/** * @author zhouyanxiang * @create 2020-07-2020/7/31-15:33 */public class Square extends Shape {    public Square() {        type = "Square";    }    @Override    void draw() {        System.out.println("Inside Square::draw() method.");    }}

创建一个类,从数据库获取实体类,并把它们存储在一个 Hashtable 中。

package com.alibaba.design.prototypepattern;import java.util.Hashtable;/** * @author zhouyanxiang * @create 2020-07-2020/7/31-15:35 */public class ShapeCache {    private static Hashtable
shapeMap = new Hashtable
(); public static Shape getShape(String shapeId) { Shape cachedShape = shapeMap.get(shapeId); return (Shape) cachedShape.clone(); } // 对每种形状都运行数据库查询,并创建该形状 // shapeMap.put(shapeKey, shape); // 例如,我们要添加三种形状 public static void loadCache() { Circle circle = new Circle(); circle.setId("1"); shapeMap.put(circle.getId(),circle); Square square = new Square(); square.setId("2"); shapeMap.put(square.getId(),square); Rectangle rectangle = new Rectangle(); rectangle.setId("3"); shapeMap.put(rectangle.getId(),rectangle); }}

PrototypePatternDemo 使用 ShapeCache 类来获取存储在 Hashtable 中的形状的克隆。

package com.alibaba.design.prototypepattern;/** * @author zhouyanxiang * @create 2020-07-2020/7/31-15:37 */public class PrototypePatternDemo {    public static void main(String[] args) {        ShapeCache.loadCache();        Shape clonedShape = (Shape) ShapeCache.getShape("1");        System.out.println("Shape : " + clonedShape.getType());        Shape clonedShape2 = (Shape) ShapeCache.getShape("2");        System.out.println("Shape : " + clonedShape2.getType());        Shape clonedShape3 = (Shape) ShapeCache.getShape("3");        System.out.println("Shape : " + clonedShape3.getType());    }}

(4)该模式在源码中的体现

我们看一下Object这个对象,我们直接看一下克隆这个方法 protected native Object clone() throws CloneNotSupportedException; 很明显看出来,他是一个native的方法,接下来我们再看一个,Cloneable这个接口,public interface Cloneable, 只要看看哪些类实现这个接口呢,就知道了这个原型模式,是如何使用的,我们按一下Ctrl+T,这里面有一个定位, 直接点一下,会在下边显示出来,这里面开始搜索,在搜索的时候呢,我们再看一个类,ArrayList,相信这个类大家都是知道的, public class ArrayList
extends AbstractList
implements List
, RandomAccess, Cloneable, java.io.Serializable 他实现了Cloneable这个接口,我们看一下它是如何重写的呢, public Object clone() {
try {
ArrayList
v = (ArrayList
) super.clone(); v.elementData = Arrays.copyOf(elementData, size); v.modCount = 0; return v; } catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable throw new InternalError(e); }} 通过Arrays.copyOf这个方法把这里面的元素,copy了一份,同理HashMap这里面 public class HashMap
extends AbstractMap
implements Map
, Cloneable, Serializable 是一样的,他也实现了Cloneable这个接口,同时他也重写了克隆这个方法 @SuppressWarnings("unchecked")@Overridepublic Object clone() { HashMap
result; try { result = (HashMap
)super.clone(); } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(e); } result.reinitialize(); result.putMapEntries(this, false); return result;} // These methods are also used when serializing HashSetsfinal float loadFactor() { return loadFactor; }final int capacity() { return (table != null) ? table.length : (threshold > 0) ? threshold : DEFAULT_INITIAL_CAPACITY;} 有兴趣的可以来看一下,那在这里想说一下,就是对于原型模式,我们平时在使用的时候,一定要检对象是否和预期是一致的, 也就是说这个对象,是新创建出来的呢,还是只是创建一个引用,指向的是同一个地址,也就是说要把深克隆和浅克隆一定要 应用好,我们看一下下面搜索出来的都是实现了Cloneable这个接口的实现类,这里又很多,这个是JDK的

img

包括redission,还有redis的client,还有Spring里面的mybatis,这里面都是实现了Cloneable接口,我们看一下Cache, CacheKey,这个类也实现了Cloneable, public class CacheKey implements Cloneable CacheKey是Mybatis里面关于Cache使用的一个类,我们看一下它是如何重写的   @Override  public CacheKey clone() throws CloneNotSupportedException {
CacheKey clonedCacheKey = (CacheKey) super.clone(); clonedCacheKey.updateList = new ArrayList(updateList); return clonedCacheKey; } 这里面可以看到,首先是super.clone(),然后强转一个新的出来,然后把里面的List赋值成一个新的List,并把这个元素放到 新的List里面,进行返回,这样就保证了ArrayList,是一个新创建的ArrayList,但是注意里面的updateList private List updateList; 这个又是一个List,有兴趣的,建议可以试一下,克隆出来的里面的,这个元素,是相同的对象还是不同的对象,非常你们能够操作一下, 你可以模拟CacheKey来写一个类,主要是List,然后再进一步的说,如果List里面包装的,不是String,而是Date对象,我们再看一下效果, 希望能够动起手来,那接着看,下面这些是实现Cloneable接口的,包括在开源框架中,会有很多,有兴趣的可以自己挨个看一下,这里面 还是挺有意思的,那原型模式在开源框架中,使用的非常广泛,就拿CacheKey来说,这里面也是非常注重克隆出来的对象,引用问题, 所以我们在实现原型模式的时候,这一点是一定一定要注意的.

(5)原型模式的优缺点

  • 优点:

    1、性能提高。

    2、逃避构造函数的约束。

  • 缺点:

    1、配备克隆方法需要对类的功能进行通盘考虑,这对于全新的类不是很难,但对于已有的类不一定很容易,特别当一个类引用不支持串行化的间接对象,或者引用含有循环结构的时候。

    2、必须实现 Cloneable 接口。

转载地址:http://meurn.baihongyu.com/

你可能感兴趣的文章
.NET Core微服务开发选项
查看>>
探讨NET Core数据进行3DES加密或解密弱密钥问题
查看>>
Vue 3拖更,尤雨溪介绍最新进展
查看>>
如何利用.NETCore向Azure EventHubs准实时批量发送数据?
查看>>
WPF 框架全构建环境虚拟机硬盘分享
查看>>
ABP框架 v3.0 已发布!
查看>>
使用.Net Core实现的一个图形验证码
查看>>
.NET 开源项目 StreamJsonRpc 介绍[中篇]
查看>>
Blazor带我重玩前端(三)
查看>>
基于.NetCore3.1系列 —— 认证授权方案之授权揭秘 (下篇)
查看>>
实现业务数据的同步迁移 · 思路一
查看>>
龙芯开源社区上线.NET主页
查看>>
eShopOnContainers 知多少[11]:服务间通信之gRPC
查看>>
闲谈设计模式
查看>>
平台or职位,你怎么选?
查看>>
骚年快答 | 技术中台与业务中台都是啥?
查看>>
骚年快答 | 微服务架构中的BFF到底是啥?
查看>>
设计模式之适配器模式
查看>>
如何利用Gitlab-CI持续部署到远程机器?
查看>>
.NET Core + K8S + Loki 玩转日志聚合
查看>>