欢迎浏览我的博客 获得更多精彩文章
https://boyn.top
什么是享元模式
在Java的包装类,如Integer,Boolean,Byte等等中,都用到了一种预先声明常用值的设计模式,这种共享常用对象的思路,就叫做享元模式,是共享的轻量级元素
下面就用Integer类为例来说明这个模式是怎么工作的
Integer的三种创建方法
在使用包装类的时候,我们通常有两种方法来对其进行创建
- 使用Java的自动装箱机制
- 使用new运算符
- 使用类的静态方法valueOf
第一种其实与第三种是一样的,这个我们在后面会进行说明
用new运算符也没什么好说的,其实就是创建了一个新的对象,并没有用到享元模式
valueOf方法
在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);
}
这一段十分通俗易懂,唯一不了解的就是,IntegerCache是什么呢?观察他的源码,我们可以知道,这是一个缓存的存储类,定义在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() {}
}
我们可以看到,上方valueOf方法中,将i与IntegerCache.low,IntegerCache.high进行比较,就是观察他有没有在缓存的区间内,如果有,直接返回缓存好的对象,如果没有,则会new一个新的对象
在这里,将常用的整数值(-128~127)进行缓存起来,以防止多次new新对象造成的消耗.我们就是将这种模式叫做享元模式.
在最后,我们看一下,为什么说Integer创建时,自动装箱方法和valueOf方法是一样的.我们来看一下以下的代码
public static void main(String[] args) {
Integer i1 = 127;
Integer i2 = 127;
System.out.println(i1==i2);
Integer i3 = 128;
Integer i4 = 128;
System.out.println(i3==i4);
}
将函数运行后,我们发现第一个输出true,第二个输出false,这就说明,在自动装箱时,会调用valueOf方法,这样一来,-128~127的值就会直接从IntegerCache里面取,所以对内存地址进行比较也就是会返回true了