0
点赞
收藏
分享

微信扫一扫

享元模式在包装类中使用

定义

它使用共享对象,用来尽可能减少内存使用量以及分享资讯给尽可能多的相似对象;它适合用于大量对象只是重复因而导致无法令人接收的使用大量内存。通常对象中的部分状态是可以分享。常见做法是把他们放在外部数据结构,当需要使用时再将它们传递给享元。
享元模式的主要优点是:相同对象只要保存一份,这降低了系统中对象的数量,从而降低了系统中细粒度对象给内存带来的压力。
其主要缺点是:
为了使对象可以共享,需要将一些不能共享的状态外部化,这将增加程序的复杂性。
读取享元模式的外部状态会使得运行时间稍微变长。

包装类案例

public class Test1 {
    public static void main(String[] args) {
        Integer x1 = new Integer(10);
        Integer x2 = new Integer(10);
        System.out.println(x1 == x2);//false
        System.out.println(x1.equals(x2));//true

        Integer x3 = new Integer(128);
        Integer x4 = new Integer(128);
        System.out.println(x3 == x4);//false
        System.out.println(x3.equals(x4));//true

        Integer x5 = 10;
        Integer x6 = 10;
        System.out.println(x5 == x6);//true
        System.out.println(x5.equals(x6));//true

        Integer x7 = 128;
        Integer x8 = 128;
        System.out.println(x7 == x8);//false
        System.out.println(x7.equals(x8));//true
    }
}

上述例子中,因为使用new关键字创建出来的是两个不同的对象,对象存储在堆内存中,而双等于判断的是对象地址,所以打印结果为false,而重写的equals方法比较的是值,所以打印结果为true。
而不适用new关键字的情况下,Integer变量指向的是java常量池中的对象,所以双等判断是相等的,而该享元模式下,只预处理了-128到127范围内的常量,因此在赋值128时相当于new了对象,而并非直接使用常量池的常量,所以双等判断的结果是false

底层代码

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

相关推荐

0 条评论