Back to Posts

享元模式与Integer的valueOf方法

Posted in DesignPattern

Patterns网站上,举出了一个运用享元模式的栗子,自己试了一遍感觉还是比较陌生,还好它有列举哪些地方也使用了享元模式,比如Integer的valueOf()方法;

Integer的valueOf(int i)方法,会判断传入的i是否在指定的范围内:

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

这里的low和high是-128和127(high在跟踪源码中可以看到可以通过java.lang.Integer.IntegerCache.high设置的值获取)

IntegerCache是个静态内部类,会在该类中,为-128~127的int值创建好对应的封装类型;

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() {}
    }

所以有的人会问,Integer i1 = Integer.valueOf(1);Integer i2 = Integer.valueOf(2); i1 == i2为啥是true?
原来valueOf方法返回的封装类型,其指定范围内的元素被视为经常要使用到的,没必要每次都为其开辟空间;所以预先为其创建好了

对于享元模式,实现的方式有很多种,个人觉得只要某个类型的实例,在一定的范围内经常用到,只要将其缓存起来(一般指的是Java内存中),需要的时候直接取出来;就算是享元模式了

你看那个人好像一条狗啊

Read Next

设计模式——适配器模式与大黄蜂