设计模式 - 原型模式

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

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

介绍

  • 意图:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象
  • 主要解决:在运行期建立和删除原型。
  • 何时使用:
    1. 当一个系统应该独立于它的产品创建,构成和表示时
    2. 当要实例化的类是在运行时刻指定时,例如,通过动态装载
    3. 为了避免创建一个与产品类层次平行的工厂类层次时
    4. 当一个类的实例只能有几个不同状态组合中的一种时。建立相应数目的原型并克隆它们可能比每次用合适的状态手工实例化该类更方便一些。
  • 如何解决:利用已有的一个原型对象,快速地生成和原型对象一样的实例。
  • 优点:
    1. 性能提高
    2. 逃避构造函数的约束
  • 缺点:
    • 1. 配备克隆方法需要对类的功能进行通盘考虑,这对于全新的类不是很难,但对于已有的类不一定很容易,特别当一个类引用不支持串行化的间接对象,或者引用含有循环结构的时候
    • 2. 必须实现 Cloneable 接口

实现

1. 创建一个形状抽象类,实现Cloneable接口

/**
 * 形状抽象类,实现Cloneable接口
 * @author remainsu
 * @version 1.0 2019-06-14
 */
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;
    }
    
    /**
     * 重写clone()
     */
    @Override
    protected Object clone() {
        
        Object clone = null;
        try {
            clone = super.clone();
            
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return clone;
    }
}

2. 创建继承上述抽象类的具体形状的实体类

/**
 * 圆形 实体类,继承Shape抽象类
 * @author remainsu
 * @version 1.0 2019-06-14
 */
public class Circle extends Shape {

    public Circle() {
        type = "Circle";
    }
    
    @Override
    public void draw() {
        System.out.println("This is Circle draw() .");
    }
}
public class Square extends Shape {

    public Square() {
        type = "Square";
    }
    
    @Override
    public void draw() {
        System.out.println("This is Square draw() .");
    }
}
public class Rectangle extends Shape {

    public Rectangle() {
        type = "Rectangle";
    }
    
    @Override
    public void draw() {
        System.out.println("This is Rectangle draw() .");
    }
}

3. 创建形状实体缓存类(事先将new好的形状缓存起来,每次使用的时候,直接取出并clone)

/**
 * 形状实体缓存类(事先将new好的形状缓存起来,每次使用的时候,直接取出并clone)
 * @author remainsu
 * @version 1.0 2019-06-14
 */
public class ShapeCache {
    
    private static HashMap<String, Shape> mapShape = new HashMap<>();
    
    /**
     * 通过clone返回形状实体
     * @param id
     * @return
     */
    public static Shape getShape(String id) {
        Shape shapeCache = mapShape.get(id);
        return (Shape) shapeCache.clone();
    }
    
    /**
     * 缓存形状实体
     */
    public static void loadShape() {
        
        Circle circle = new Circle();
        mapShape.put("1", circle);
        
        Square square = new Square();
        mapShape.put("2", square);
        
        Rectangle rectangle = new Rectangle();
        mapShape.put("3", rectangle);
    }
}

4. 测试类

/**
 * 原型模式测试类
 * @author remainsu
 * @version 1.0 2019-06-14
 */
public class Test {
    
    public static void main(String[] args) {
        ShapeCache.loadShape();
        
        Shape cloneShape1 = ShapeCache.getShape("1");
        cloneShape1.setId("111");
        System.out.println(cloneShape1.getId()+"---"+cloneShape1.getType()); 
        cloneShape1.draw();
        
        System.out.println(ShapeCache.getShape("2").getType()); 
        System.out.println(ShapeCache.getShape("3").getType()); 
        
    }
}

运行结果:

111---Circle
This is Circle draw() .
Square
Rectangle

参考

  1. https://www.runoob.com/design-pattern/prototype-pattern.html
  2. https://mp.weixin.qq.com/s?__biz=MzI4Njc5NjM1NQ==&mid=2247485830&idx=1&sn=a3164e131d4ed08cc6cfcdaec4425ff4&chksm=ebd636aadca1bfbcd1df059f9795350157c600f37238ba2f334e03064e25e8359b0acfc177b4&scene=21#wechat_redirect

猜你喜欢

转载自www.cnblogs.com/remainsu/p/she-ji-mo-shi--yuan-xing-mo-shi.html