享元模式

运用共享技术有效地支持大量细粒度对象的复用.

结构

  • 抽象享元类
  • 具体享元类
  • 非共享具体享元类
  • 享元工厂类

      举例: java.lang.Integer#valueOf(int)
    

    Integer-valueOf

    享元模式

Demo

抽象享元类
public interface Ball {
    String ballInfo();
}
具体享元类
public class Basketball implements Ball {

    private String number;

    private String info;

    public Basketball(String info) {
        this.info = info;
    }

    @Override
    public String ballInfo() {
        return info;
    }
}
享元工厂
public class BallFactory {

    private static final HashMap<String, Ball> BALL_HASH_MAP = new HashMap<>();

    public Ball getBall(String name) {

        Ball ball = BALL_HASH_MAP.get(name);

        if (ball == null) {
            System.out.println(name + "不存在, 创建新对象");
            ball = new Basketball(name + "篮球");
            BALL_HASH_MAP.put(name, ball);
        }

        return ball;
    }

}
Test
public class FlyWeightTest {

    public static void main(String[] args) {

        BallFactory ballFactory = new BallFactory();

        Ball num1 = ballFactory.getBall("num1");
        Ball num11 = ballFactory.getBall("num1");
        System.out.println(num1.equals(num11));
        ballFactory.getBall("num3");
        ballFactory.getBall("num2");

    }
}

结论

  • 减少内存中对象的数量, 节约系统资源, 提高系统性能
  • 系统相对较复杂, 尤其是享元对象存在状态属性时, 要注意状态

   版权声明

文章作者: liuzhihang
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源!