本文共 6500 字,大约阅读时间需要 21 分钟。
代码地址:
原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。例如,一个对象需要在一个高代价的数据库操作之后被创建。我们可以缓存该对象,在下一个请求时返回它的克隆,在需要的时候更新数据库,以此来减少数据库调用。
何时使用:
1、当一个系统应该独立于它的产品创建,构成和表示时。
2、当要实例化的类是在运行时刻指定时,例如,通过动态装载。
3、为了避免创建一个与产品类层次平行的工厂类层次时。
4、当一个类的实例只能有几个不同状态组合中的一种时。建立相应数目的原型并克隆它们可能比每次用合适的状态手工实例化该类更方便一些。
**如何解决:**利用已有的一个原型对象,快速地生成和原型对象一样的实例。
关键代码:
1、实现克隆操作,在 JAVA 继承 Cloneable,重写 clone(),在 .NET 中可以使用 Object 类的 MemberwiseClone() 方法来实现对象的浅拷贝或通过序列化的方式来实现深拷贝。
2、原型模式同样用于隔离类对象的使用者和具体类型(易变类)之间的耦合关系,它同样要求这些"易变类"拥有稳定的接口。
应用实例: 1、细胞分裂。 2、JAVA 中的 Object clone() 方法。
创建一个实现了 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; }}
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."); }}
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."); }}
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 HashtableshapeMap = 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()); }}
我们看一下Object这个对象,我们直接看一下克隆这个方法 protected native Object clone() throws CloneNotSupportedException; 很明显看出来,他是一个native的方法,接下来我们再看一个,Cloneable这个接口,public interface Cloneable, 只要看看哪些类实现这个接口呢,就知道了这个原型模式,是如何使用的,我们按一下Ctrl+T,这里面有一个定位, 直接点一下,会在下边显示出来,这里面开始搜索,在搜索的时候呢,我们再看一个类,ArrayList,相信这个类大家都是知道的, public class ArrayListextends 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的
包括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
优点:
1、性能提高。
2、逃避构造函数的约束。
缺点:
1、配备克隆方法需要对类的功能进行通盘考虑,这对于全新的类不是很难,但对于已有的类不一定很容易,特别当一个类引用不支持串行化的间接对象,或者引用含有循环结构的时候。
2、必须实现 Cloneable 接口。
转载地址:http://meurn.baihongyu.com/