从一个有趣的题目理解享元模式
2015-12-24 22:24
211 查看
刚刚工作的时候看设计模式,编程功底太薄弱,看着例子简单,看完却感觉什么也没有学到,尤其是一些比较少见的设计模式。最近看到一条题目,想到之前设计模式里面的享元模式,特分享给大家看看。
题目有点意思,分别输出true、false。
为什么呢?
这里用到了装箱,我们看反编译代码,就容易看出端倪。
进去看vauleOf代码,就知道为什么了
原来为了提高性能少创建对象,jdk吧-128到127都缓存起来了,所以这个范围内都返回同一个实例,不在这个范围的就new一个出来。
这就是我理解的享元模式
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一个出来。
这就是我理解的享元模式
相关文章推荐
- Oracle系列之索引
- 网络基础
- Apache搭建多个站点方法详解
- Android编程技巧之随意从当前Activity退出应用
- Tracking-Learning-Detection原理分析
- 随想录(关于smp的均衡负载)
- Exception 'yii\db\Exception' with message 'SQLSTATE[HY000] [2002] No such file or directory’错误的解决方法
- Ubuntu下为Firefox安装Adobe Flash Player
- Hdu 2037 之解题报告
- 20151217:Web之Repeater使用:删除
- Creating and Using a Temporary File
- /etc/ld.so.conf文件
- Linux进程控制
- 一起talk C栗子吧(第八十二回:C语言实例--简单圣诞树)
- Oracle系列之序列
- CentOS install GCC-4.8.5
- POJ2778 DNA sequence[自动AC机&矩阵快速幂]
- redis之集合类型(set)
- 分支与循环2
- HDOJ 1717 小数化分数2 (数学,循环小数化分数详细讲解)