继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

从一道题目看享元设计模式

晓风轻
关注TA
已关注
手记 22
粉丝 1.1万
获赞 1073

用JDK的一个小特性、小代码来理解一个模式。

刚刚工作的时候看设计模式,编程功底太薄弱,看着例子简单,看完却感觉什么也没有学到,尤其是一些比较少见的设计模式。最近看到一条题目,想到之前设计模式里面的享元模式,特分享给大家看看。

public class IntegerDemo
{

    public static void main(String[] args)
    {
        Integer a1 = 127;
        Integer a2 = 127;

        System.out.println(a1 == a2);

        Integer a3 = 129;
        Integer a4 = 129;

        System.out.println(a3 == a4);
    }
}

题目有点意思,分别输出true、false。

为什么呢?

这里用到了装箱,我们看反编译代码,就容易看出端倪。

import java.io.PrintStream;

public class IntegerDemo
{
  public static void main(String[] args)
  {
    Integer a1 = Integer.valueOf(127);
    Integer a2 = Integer.valueOf(127);

    System.out.println(a1 == a2);

    Integer a3 = Integer.valueOf(129);
    Integer a4 = Integer.valueOf(129);

    System.out.println(a3 == a4);
  }
}

进去看vauleOf代码,就知道为什么了

    /**
     * Returns a {@code Integer} instance for the specified integer value.
     * <p>
     * If it is not necessary to get a new {@code Integer} instance, it is
     * recommended to use this method instead of the constructor, since it
     * maintains a cache of instances which may result in better performance.
     *
     * @param i
     *            the integer value to store in the instance.
     * @return a {@code Integer} instance containing {@code i}.
     * @since 1.5
     */
    public static Integer valueOf(int i) {
        return  i >= 128 || i < -128 ? new Integer(i) : SMALL_VALUES[i + 128];
    }

    /**
     * A cache of instances used by {@link Integer#valueOf(int)} and auto-boxing
     */
    private static final Integer[] SMALL_VALUES = new Integer[256];

    static {
        for (int i = -128; i < 128; i++) {
            SMALL_VALUES[i + 128] = new Integer(i);
        }
    }

原来为了提高性能少创建对象,jdk吧-128到127都缓存起来了,所以这个范围内都返回同一个实例,不在这个范围的就new一个出来。

这就是我理解的享元模式

设计扩展

我们在自己的系统里面,如果某类对象大量使用,而这类对象又很少或者不会修改,我们就可以使用享元模式,最常见的就是把系统里面的用户信息。这样每次都返回同一个对象,不需要频繁创建和回收对象,有利于提升系统性能。

打开App,阅读手记
9人推荐
发表评论
随时随地看视频慕课网APP