设计模式——享元模式

什么是享元模式

池技术是享元模式运用的一个经典了,享元模式是使用户共享相似对象的一种设计模式,比如在数据库连接池中,里面会放置很多已经创建好的连接对象,如果要使用相似的对象可以直接在池中取,这样就节省了大量对象的创建。所以,享元模式一般运用在系统底层来提高系统性能,像String常量池,数据库连接池,缓冲池中都有使用。

UML

UML

这里最重要的就是FlyWeightFactory,这里面一般会存放一个map用来存储需要共享的元对象,当我们需要创建新对象的时候,会先检查池中是否已经有相似对象,如果有直接从池中取。

外部状态和内部状态

内部状态指的是共享对象的一些不可改变的状态,它们是固定的,比如我们需要共享一些棋子,对于棋子来说,其颜色黑白两色是它的内部状态是共享出去的,而且不会变。而棋子的内部状态来说可以使棋子的位置,这是一直会发生变化的,而且它不是共享出去的,是由使用者决定的。

享元模式在Integer中的应用

在Integer的静态方法valueOf中我们创造一个Integer对象会先从预先定义好的缓冲池中去取。

Integer的valueOf方法

如果范围是-128~127会直接从缓冲池中取出对象,不然再创建新对象,这样就能减少对象的频繁创建。

我们可以看到缓冲池中会预先给我们存放元对象于数组中(在静态块中执行)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];

static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;

cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);

// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}

private IntegerCache() {}
}
-------------本文结束感谢阅读-------------