享元模式(Flyweight Pattern)

2018-12-30  本文已影响0人  群众里面有坏人呐

定义

享元模式(Flyweight Pattern),又称轻量级模式(这也是其英文名为FlyWeight的原因),通过共享技术有效地实现了大量细粒度对象的复用。
内部状态:在享元对象内部不随外界环境改变而改变的共享部分。
外部状态:随着环境的改变而改变,不能够共享的状态就是外部状态。

角色

实例

享元接口

public interface Shape {
    void draw();
}

具体享元类

public class Circle implements Shape {
    String color;

    public Circle(String color) {
        this.color = color;
    }

    @Override
    public void draw() {
        System.out.println("draw a circle, and the color is "+color);
    }
}

享元工厂类

public class ShapeFactory {
    public int SUM=0;
    public int SUM_OBJECT=0;
    public static ConcurrentHashMap<String, Shape> map = new ConcurrentHashMap<String, Shape>();
    public Shape getShape(String color){
        if (map.get(color) == null) {
            synchronized (map) {
                if (map.get(color) == null) {
                    map.put(color, new Circle(color));
                    SUM_OBJECT++;
                }
            }
        }
        SUM++;
        return map.get(color);
    }
}

测试代码

public class Test {
    public static void main(String[] args) {
        ShapeFactory factory = new ShapeFactory();
        factory.getShape("red").draw();
        factory.getShape("black").draw();
        factory.getShape("blue").draw();
        factory.getShape("green").draw();
        factory.getShape("red").draw();
        factory.getShape("blue").draw();
        factory.getShape("red").draw();

        System.out.println("共画了"+factory.SUM+"个圆");
        System.out.println("共产生了"+factory.SUM_OBJECT+"个对象");
    }
}

运行结果

draw a circle, and the color is red
draw a circle, and the color is black
draw a circle, and the color is blue
draw a circle, and the color is green
draw a circle, and the color is red
draw a circle, and the color is blue
draw a circle, and the color is red
共画了7个圆
共产生了4个对象
上一篇下一篇

猜你喜欢

热点阅读