创建型设计模式(四)原型模式

一、一句话背景

假如我是个设计大佬,我经常需要调用服务去获取各种基本图形来组合我的素材,那重复访问的工作就会很多,那在没有外置缓存的情况下,可以考虑使用原型模式来玩~

二、使用场景

需要重复生成多次相同对象的场景。

如:重复取相同对象使用时

三、模型分析

图形原型:抽象类,原型父类,用于扩展子类对象,并进行复用

具体图形:类,图形父类的多样化拓展

模拟缓存:类,用于模拟缓存具体的对象,并提供复制方法

四、代码分析

图形原型

/**
 * 形状类,原型父类,用于扩展子类对象,并进行复用
 */
public abstract class Shape implements Cloneable {

    private String id;
    protected String type;

    public 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 Circle extends Shape {

    public Circle() {
        type = "Circle";
    }

    @Override
    public void draw() {
        System.out.println("Inside Circle::draw() method.");
    }
}
/**
 * 矩形类
 */
public class Rectangle extends Shape {

    public Rectangle(){
        type = "Rectangle";
    }

    @Override
    public void draw() {
        System.out.println("Inside Rectangle::draw() method.");
    }
}
/**
 * 正方形类
 */
public class Square extends Shape {

    public Square() {
        type = "Square";
    }

    @Override
    public void draw() {
        System.out.println("Inside Square::draw() method.");
    }
}

模拟缓存

/**
 * 模拟缓存类,用于复制拓展的对象
 */
public class ShapeCache {

    //这个map里存好了对象,用的时候直接调用本类的getShape来clone就好
    private static Hashtable<String, Shape> shapeMap = new Hashtable<String, Shape>();

    //static可以把这个方法给其他类调用,直接clone设置好的map里的对象,就不用每次都new一个对象
    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);
    }
}

克隆调用

/**
 * 模拟克隆调用
 */
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());
    }
}

 

原文地址:https://www.cnblogs.com/riches/p/11214511.html