享元模式
享元模式通过共享技术实现了对相同或者相似对象的重用,它通过提供一个享元池,为客户端的每次调用提供一个享元对象使用,在逻辑上的每一次调用都会有一个对象与之对应,然而在物理上它们却享有同一个地址值。
享元对象能够做到共享的关键是区分了内部状态和外部状态。
内部状态:存储在享元对象内部并且不会随着环境改变而改变的状态,内部状态始终可以共享。
外部状态:随着环境改变而改变,不可以共享的状态。外部状态之间是相互独立的。
定义
运用共享技术有效地支持大量细粒度对象的复用。
结构
- Flyweight抽象享元类。抽象类或者接口,定义了享元类的公共方法,并且可以接收不可共享的外部状态。
- ConcreteFlyweight具体享元类。实现了抽象享元类的方法,可以设计为单例模式,存储着享元对象的内部状态,可以接收外部状态。
- FlyweightFactory享元工厂类。用于创建并管理享元对象,它针对抽象享元类编程,将各种类型的享元对象存储在一个享元池中,享元池一般设计为一个键值对集合。
实例
package flyweight;
public interface Leaf {
public void show(Color color);
}
package flyweight;
import java.util.HashMap;
import java.util.Map;
public class LeafFactory {
private Map<String, Leaf> leafMap;
public LeafFactory() {
this.leafMap = new HashMap<>();
leafMap.put("willow", new WillowLeaf());
}
public Leaf getLeaf(String key) {
return leafMap.get(key);
}
}
package flyweight;
public class WillowLeaf implements Leaf {
@Override
public void show(Color color) {
System.out.println(color.getColor() + "的柳树叶子");
}
}
package flyweight;
public class Color {
private String color;
public Color(String color) {
super();
this.color = color;
}
public String getColor() {
return this.color;
}
}
package flyweight;
public class Test {
public static void main(String[] args) {
LeafFactory factory = new LeafFactory();
Leaf leaf = factory.getLeaf("willow");
leaf.show(new Color("红色"));
}
}
// 红色的柳树叶子
Integer中的享元模式
/**
* Cache to support the object identity semantics of autoboxing for values between
* -128 and 127 (inclusive) as required by JLS.
*
* The cache is initialized on first usage. The size of the cache
* may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
* During VM initialization, java.lang.Integer.IntegerCache.high property
* may be set and saved in the private system properties in the
* sun.misc.VM class.
*/
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() {}
...
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
...
}
Integer中有一个内部类IntegerCache, 相当于我们享元模式结构中的享元工厂类。它在初始化的时候负责缓存-128到127(可以设置)的所有Integer对象到缓存池中,调用Integer的相关方法的时候,优先从常量池中获取,如果常量池中没有,那么创建一个新的Integer对象。如下面示例,所以无论在任何时候对Integer的比较都建议通过equals方法。
public static void main(String[] args) {
Integer a = 100;
Integer b = 100;
Integer c = 150;
Integer d = 150;
System.out.println(a == b);
System.out.println(c == d);
}
// true
// false
优点
- 享元模式可以减少内存中对象的数量,使相同或者相似的对象在内存中只有一份,从而减少系统资源的消耗,提高性能。
- 享元模式的外部状态独立,不会影响内部状态,使享元对象可以在不同环境中使用。
适用场景
- 系统中有大量相同或者相似对象,造成内存的大量浪费。
- 对象可以区分出明显的内部状态和外部状态。
- 系统对于相同对象的重复调用比较大,需要维护一个享元池。