1. 享元模式
1.1 介绍
享元模式(Flyweight Pattern)主要用于减少创建对象的数量,以减少内存占用和提高性能。这种类型的设计模式属于结构型模式,它提供了减少对象数量从而改善应用所需的对象结构的方式。
享元模式尝试重用现有的同类对象,如果未找到匹配的对象,则创建新对象。我们将通过创建 5 个对象来画出 20 个分布于不同位置的圆来演示这种模式。由于只有 5 种可用的颜色,所以 color 属性被用来检查现有的 Circle 对象。
1.2 优缺点
优点
- 大大减少对象的创建,降低系统的内存,使效率提高
缺点
- 提高了系统的复杂度,需要分离出外部状态和内部状态,而且外部状态具有固有化的性质,不应该随着内部状态的变化而变化,否则会造成系统的混乱。
1.3 使用场景
- 系统有大量相似对象
- 需要缓冲池的场景
1.4 注意事项
- 注意划分外部状态和内部状态,否则可能会引起线程安全问题
- 这些类必须有一个工厂对象加以控制。
2. 案例代码
现在我有了娃娃机,但是每次买娃娃需要很多钱,所以我需要将娃娃保存起来,下次直接使用而不是去买,如果没有才要去买,恰巧娃娃机有一个娃娃盒子,可以放置我购买的娃娃。
public class CraneMachine {
HashMap<String, DecoratorRagdoll> hashMap; // 娃娃盒子
public CraneMachine() {
this.hashMap = new HashMap<>();
}
public DecoratorRagdoll getRagdoll(String ragdollName, String skirtColor){
// 找到娃娃
if(hashMap.containsKey(ragdollName+skirtColor)){
return hashMap.get(ragdollName+skirtColor);
}else{
Ragdoll ragdoll = Ragdoll.getRagdoll(ragdollName);
Skirt skirt = Skirt.getSkirt(skirtColor);
DecoratorRagdoll build = this.build(ragdoll, skirt);
hashMap.put(ragdollName+skirtColor, build);
return build;
}
}
private DecoratorRagdoll build(Ragdoll ragdoll, Skirt skirt){
DecoratorRagdoll decoratorRagdoll = new DecoratorRagdoll();
decoratorRagdoll.setRagdoll(ragdoll);
decoratorRagdoll.setSkirt(skirt);
return decoratorRagdoll;
}
}
/** * 享元模式 * *@Author cly *@Date 2021/08/31 16:33 *@Version 1.0 */
public class Flyweight {
public static void main(String[] args) {
CraneMachine craneMachine = new CraneMachine();
DecoratorRagdoll ragdoll = craneMachine.getRagdoll("太平公主", "红色");
DecoratorRagdoll ragdoll1 = craneMachine.getRagdoll("太平公主", "白色");
DecoratorRagdoll ragdoll2 = craneMachine.getRagdoll("太平公主", "红色");
System.out.println(ragdoll == ragdoll1); // false
System.out.println(ragdoll == ragdoll2); // true
}
}
3. 源码实现
3.1 包装类
享元模式比较经典的应用就是 JDK 中部分基本类型的包装类,缓存了一定数值范围的对象,valueOf 方法转换为包装对象时,如果值在缓存范围内,即返回缓存对象。
- Byte,缓存了 -128 ~ 127
- Short,缓存了 -128 ~ 127
- Character,缓存了 0 ~ 127
- Integer,缓存了 -128 ~ 127,JVM 启动参数 -XX:AutoBoxCacheMax 可以设置范围的最大值
- Long,缓存了 -128 ~ 127
- Boolean,缓存了 true 和 false 对象
不同版本的 JDK 机制不一样,这里说的是 JDK 8。
为啥 Float、Double 没缓存呢?因为计算机可表示的两个整数之间的浮点数太多太多,无法确定使用频率,缓存没有意义。
public final class Integer extends Number implements Comparable<Integer> {
public static Integer valueOf(int i) {
//在 IntegerCache 中缓存了 [low,high]
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
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() {
}
}
}