美文网首页
设计模式-享元模式(结构型)

设计模式-享元模式(结构型)

作者: NealLemon | 来源:发表于2019-08-12 21:55 被阅读0次

    定义

    提供了减少对象数量从而改善应用所需的对象结构的方式。

    运用共享技术有效地支持大量细粒度的对象。

    减少对象的数量,从而减少内存的占用,进而提高系统的运行速度。

    扩展

    • 内部状态:在对象的内部,不会随着外部改变而改变。
    • 外部状态:随着环境改变而改变。

    适用场景

    • 系统底层开发,以便解决系统性能问题。(数据库连接池)
    • 系统中有大量的相似对象,需要缓冲池的场景。

    优点

    • 减少对象的创建,降低内存中对象的数量,降低系统的内存,提高效率。
    • 减少内存之外的其他资源占用。

    缺点

    • 线程安全问题。
    • 使逻辑和程序复杂化。

    其他源码使用

    由于享元模式就是复用对象的思想,一般使用HashMap等数据结构作为缓存容器。因此就不举代码演示了。我们直接来看一下JDK源码中使用享元模式的部分。

    比较有代表性的类就是Integer这个类。我们来看一下他的valueOf()方法。

    /**
     * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} instance is not
     * required, this method should generally be used in preference to
     * the constructor {@link #Integer(int)}, as this method is likely
     * to yield significantly better space and time performance by
     * caching frequently requested values.
     *
     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.
     *
     * @param  i an {@code int} value.
     * @return an {@code Integer} instance representing {@code i}.
     * @since  1.5
     */
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
    

    这里我们可以看到 在调用valueOf的时候,方法中先做了缓存判断,那么我们来看一下这缓存中存储的是什么?

    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对象的值大于等于 -128 小于等于127时,它所返回的都是缓存好的对象。

    小结

    在这个设计模式中,其核心思想就是对象的缓存以及复用,在涉及底层开发的时候,相信由于系统瓶颈和效率方面的考虑,会去使用这种模式。

    相关文章

      网友评论

          本文标题:设计模式-享元模式(结构型)

          本文链接:https://www.haomeiwen.com/subject/xegpjctx.html