Java享元模式

享元模式(Flyweight Pattern)主要用于减少创建对象的数量,以减少内存占用和提高性能

意图: 运用共享技术有效地支持大量细粒度的对象。

主要解决: 在有大量对象时,有可能会造成内存溢出,我们把其中共同的部分抽象出来,如果有相同的业务请求,直接返回在内存中已有的对象,避免重新创建。

何时使用: 1、系统中有大量对象。 2、这些对象消耗大量内存。 3、这些对象的状态大部分可以外部化。

如何创建: 用唯一标识码判断,如果在内存中有,则返回这个唯一标识码所标识的对象。

应用实例: 1、JAVA 中的 String,如果有则返回,如果没有则创建一个字符串保存在字符串缓存池里面。 2、数据库的数据池。

优点: 大大减少对象的创建,降低系统的内存,使效率提高。

缺点: 提高了系统的复杂度,需要分离出外部状态和内部状态,而且外部状态具有固有化的性质,不应该随着内部状态的变化而变化,否则会造成系统的混乱。

使用场景: 1、系统有大量相似对象。 2、需要缓冲池的场景。

注意事项: 1、注意划分外部状态和内部状态,否则可能会引起线程安全问题。 2、这些类必须有一个工厂对象加以控制。

案例

享元模式尝试重用现有的同类对象,如果未找到匹配的对象,则创建新对象。我们将通过创建 5 个圆对象来画出 不同样式的圆 以颜色来区别对象

java享元设计模式内部状态和外部状态 享元模式 java_享元模式

java享元设计模式内部状态和外部状态 享元模式 java_java_02

画 接口

public interface Shape {
    void draw();
}

画圆 实现类

public class Circle implements Shape {
    private String color;
    private int x;
    private int y;
    private int radius;

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

    public void setX(int x) {
        this.x = x;
    }

    public void setY(int y) {
        this.y = y;
    }

    public void setRadius(int radius) {
        this.radius = radius;
    }

    @Override
    public void draw() {
        System.out.println("圆形: Draw() [Color : " + color
                +", x : " + x +", y :" + y +", 半径 :" + radius);
    }
}

使用该工厂,通过传递颜色信息来获取实体类的对象。

public class ShapeFactory {
    private static final HashMap<String, Shape> circleMap = new HashMap<>();

    //以颜色来区别 圆形对象  如果 HashMap中有此颜色的对象那么 直接返回 如果没有 那么就创建一个
    public static Shape getCircle(String color) {
        Circle circle = (Circle)circleMap.get(color);

        if(circle == null) {
            circle = new Circle(color);  //创建圆形
            circleMap.put(color, circle); //将新的 颜色圆形 存入
        }
        return circle;
    }
}

测试

public class FlyweightPatternDemo {
    private static final String colors[] = { "红色", "绿色", "蓝色", "黑色", "白色" };  //5种颜色
    private static String getRandomColor() { //随机从5中颜色中获取一个
        return colors[(int)(Math.random()*colors.length)];
    }
    private static int getRandomX() {//随机 x
        return (int)(Math.random()*100 );
    }
    private static int getRandomY() { //随机 y
        return (int)(Math.random()*100);
    }


    public static void main(String[] args) {

        for(int i=0; i < 10; ++i) {
            Circle circle = (Circle) ShapeFactory.getCircle(getRandomColor());
            circle.setX(getRandomX());
            circle.setY(getRandomY());
            circle.setRadius(100);
            circle.draw();
        }
    }

}

圆形: Draw() [Color : 黑色, x : 47, y :0, 半径 :100
圆形: Draw() [Color : 黑色, x : 58, y :67, 半径 :100
圆形: Draw() [Color : 红色, x : 75, y :27, 半径 :100
圆形: Draw() [Color : 黑色, x : 47, y :47, 半径 :100
圆形: Draw() [Color : 白色, x : 36, y :14, 半径 :100
圆形: Draw() [Color : 黑色, x : 75, y :15, 半径 :100
圆形: Draw() [Color : 蓝色, x : 73, y :88, 半径 :100
圆形: Draw() [Color : 绿色, x : 5, y :88, 半径 :100
圆形: Draw() [Color : 白色, x : 37, y :36, 半径 :100
圆形: Draw() [Color : 绿色, x : 36, y :38, 半径 :100