java中具体的23中设计模式的介绍,可以参考:http://c.biancheng.net/design_pattern/
在享元模式中,有一个很经典的案例就是Integer包装类的实现。看下如下代码:
Integer a = 1;
Integer b = 1;
System.out.println(a == b);
Integer c = 128;
Integer d = 128;
System.out.println(c == d);
这里a == b是true,而c == d是false的结果。因为Integer的源码实现中,使用了共享内存的设计理念(即享元模式),源码如下:
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
int high = 127;
cache = new Integer[(high - low) + 1]; //提前缓存127+128+1=256个Integer对象
int j = low;
for