设计模式之原型模式——Java语言描述

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

这种模式实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则适合采用这种模式。

应用实例:

  1. 细胞分裂
  2. Java中的Object.clone()方法

优点:

  1. 性能较高
  2. 逃避构造函数的约束

缺点:

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

实现

我们将创建一个抽象类Shape并且扩展了Shape类的实体类。下一步是定义类 ShapeCache,该类把shape对象存储在一个Hashtable中,并在请求的时候返回它们的克隆。

Shape抽象类

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;
   }
}

拓展实体类

public class Rectangle extends Shape {
 
   public Rectangle(){
     type = "Rectangle";
   }
 
   @Override
   public void draw() {
      System.out.println("Inside Rectangle::draw() method.");
   }
}

创建实体缓存

import java.util.Hashtable;
 
public class ShapeCache {
    
   private static Hashtable<String, Shape> shapeMap 
      = new Hashtable<String, Shape>();
 
   public static Shape getShape(String shapeId) {
      Shape cachedShape = shapeMap.get(shapeId);
      return (Shape) cachedShape.clone();
   }
 
   // 对每种形状都运行数据库查询,并创建该形状
   public static void loadCache() {
      Rectangle rectangle = new Rectangle();
      rectangle.setId("1");
      shapeMap.put(rectangle.getId(),rectangle);
   }
}

演示使用:

public class PrototypePatternDemo {
   public static void main(String[] args) {
      ShapeCache.loadCache();
 
      Shape clonedShape = (Shape) ShapeCache.getShape("1");
      System.out.println("Shape : " + clonedShape.getType());        
     
   }
}

输出结果:

Shape : Rectangle

猜你喜欢

转载自www.cnblogs.com/AmosH/p/10223564.html
今日推荐