分享程序网
首页
  • java
微服务
微前端
环境搭建
数据库
设计模式
算法
软件
解决问题
链接
首页
  • java
微服务
微前端
环境搭建
数据库
设计模式
算法
软件
解决问题
链接
  • 创建模式

    • 单例模式
    • 工厂方法模式
    • 抽象工厂模式
    • 原型模式
    • 建造者模式
  • 结构模式

    • 适配器模式
    • 桥接模式
    • 组合模式
    • 装饰器模式
    • 门面模式
    • 享元模式
    • 代理模式
  • 行为模式

    • 责任链模式
    • 命令模式
    • 迭代器模式
    • 策略模式
    • 模板方法模式

享元模式

​ 享元模式是一个非常简单的模式,它可以大大减少应用程序创建的对象,降低程序内存的占用,增强程序的性能,但它同时也提高了系统复杂性,需要分离出外部状态和内部状态,而且外部状态具有固化特性,不应该随内部状态改变而改变,否则导致系统的逻辑混乱。

​ 比如常用的数据库连接池就是享元模式。就是我们没必要在每次使用的时候去创建数据库连接对象,而是将对象保存在连接池中,这样就减少了对象的创建以及线程关闭的开销。可以看一下抽象工厂的实例。

​ 举一个例子,比如我们常用的Integer类。

public class IntegerTest {
    public static void main(String[] args) {
        Integer a = Integer.valueOf(127);
        Integer b = 127;

        Integer c = Integer.valueOf(128);
        Integer d = 128;

        System.out.println(a == b); //true
        System.out.println(c == d);
    }
}

执行结果如下:

true
false

原因就是Integer类中使用了享元模式。

	private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }

缓存了-128~127的数据。我们在使用Integer.valueOf(数字)的时候

	public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

返回的就是缓存的对象,如果超出这个范围才会创建一个新的对象。

Last Updated:
Contributors: clcheng
Prev
门面模式
Next
代理模式