从一个有趣的题目理解享元模式

本文通过一道编程题目,深入探讨了享元模式的应用。题目涉及Java中装箱操作的细节,解释了为何-128到127之间的Integer对象会返回相同的实例,而超出该范围则会新建对象。这种优化策略正是享元模式的体现,旨在减少内存中对象的数量,提高性能。
摘要由CSDN通过智能技术生成

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

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一个出来。

这就是我理解的享元模式

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值