亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

從一道題目看享元設計模式

標簽:
Java

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

这就是我理解的享元模式

设计扩展

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

點擊查看更多內容
9人點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
全棧工程師
手記
粉絲
1.1萬
獲贊與收藏
1074

關注作者,訂閱最新文章

閱讀免費教程

感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消