享元模式

来源:互联网 发布:mysql 查看访问权限 编辑:程序博客网 时间:2024/06/07 04:41

1、定义
运用共享技术,有效地支持大量细粒度对象的复用。

享元模式中,共享的内容称为内部状态,需要外部环境来设置的不能共享的内容称为外部状态。

可以通过设置不同的外部状态,使得相同的对象可以具有一些不同的特征,而相同的内部状态是可以共享的。

2、实例

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

IntegerCache是Integer中的内部类,里面定义了两个属性,high,cache,其中high在static块中给出了赋值,如果配置integerCacheHighPropValue的话,默认的high是127,low=-128。

如果i属于[-128,127],则返回cache[i+128],是IntegerCache的一个静态数组。
因此,当自动装箱的i在[-128,127]范围内,则不生成新的Integer,而是共享了一个Integer对象。(享元模式)
超出该范围的Integer才真正的new出了Integer对象。

其他的如Long,Double,Float,Boolean等类型,同Integer。

实例代码:

public static void main(String[] args) {    Integer a1 = 3;    Integer b1 = Integer.valueOf(3);    Integer a2 = 200;    Integer b2 = Integer.valueOf(200);    if (a1 == b1) {        System.out.println("a1=b1");    } else {        System.out.println("a1!=b1");    }    if (a2 == b2) {        System.out.println("a2==b2");    } else {        System.out.println("a2!=b2");    }}

输出:

a1=b1a2!=b2