您的位置:首页 > 其它

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

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

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

这就是我理解的享元模式
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: