设计模式(9)—— 结构型 ——享元(Flyweight)

版权声明:如有任何疑问,欢迎@我:[email protected] https://blog.csdn.net/qq_37206105/article/details/84148997

介绍

  • 定义:提供了减少对象数量从而改善应用所需的对象结构的方式
  • 说明:运用共享技术有效地支持大量细粒度的对象
  • 类型:结构型
  • 适用场景:
    • 常常应用于系统底层的开发,以便解决系统的性能问题(Java中String的实现,数据库的连接池)
    • 系统有大量相似对象,需要缓存池的场景。
  • 优点:
    • 减少对象的创建,降低内存中的对象数量,降低系统的内存,提高效率。
    • 减少内存之外的其它资源占用。
  • 缺点
    • 关注内/外部状态,关注线程安全问题
    • 系统,程序的逻辑复杂化
  • 扩展
    • 内部状态
    • 外部状态
  • 相关的设计模式
    • 享元模式和代理模式
    • 享元模式和单例模式

代码实现

实例代码看他人的博客:点击

再看JDK中是怎样运用的,我们首先关注这段测试代码:

Integer a = Integer.valueOf(25);
Integer b = 25;

Integer c = Integer.valueOf(1000);
Integer d = 1000;

System.out.println("a==b:"+(a==b));

System.out.println("c==d:"+(c==d));

查看输出结果:

a==b:true
c==d:false

我们查看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);
    }

注意到下面的注释说明:方法总是会缓存-128~127范围内的值(其中包含范围边界),可能会缓存在此范围外的值

     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.

于是也就很容易理解上面的代码了。
i >= IntegerCache.low && i <= IntegerCache.high先判断值是否在缓存中,如果在,那么直接从缓存中取,那么必然会共享一个内存地址。如果不在缓存中,此时才new一个新对象。

猜你喜欢

转载自blog.csdn.net/qq_37206105/article/details/84148997