Earth Guardian

You are not LATE!You are not EARLY!

0%

设计模式--结构型:享元模式

享元模式:运用共享技术有效的支持大量细粒度的对象

享元模式 Flyweight

享元模式:将对象划分为内部状态和外部状态,共享内部状态,通过共享池来减少对象的一种模式。

内部状态/外部状态

  • 内部状态
    享元对象内部不会随环境改变而改变的共享部分,称为享元对象的内部状态。也就是说,内部状态是不变的部分。
  • 外部状态
    受环境影响改变,不可共享的部分,称为享元对象的外部状态。也就是说,外部状态是变化的。

比如一堆衣服中有男女两个款式,如果需要请模特过来拍照展示,其中性别是无法改变的部分,即内部状态;而衣服款式是多变不一样的,所以款式是外部状态。在这个例子中,通过创建共享池共享性别对象。

类图结构

0057-Flyweight-uml-classdiag.png

结构解析

  • Flyweight
    抽象类,享元类,表示可以共享的抽象类。
  • ConcreteFlyweight
    实现类,具体共享类。
  • UnsharedConcreteFlyweight
    实现类,具有共享能力,但是不强制该类共享。
  • FlyweightFactory
    享元工厂,创建并管理享元对象,通过共享池保存。

示例

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// 1. Flyweight
public abstract class Flyweight {
public abstract void operation(String extrinsicState);
}

// 2. ConcreteFlyweight
public class ConcreteFlyweight extends Flyweight{
@Override
public void operation(String extrinsicState) {
System.out.println("ConcreteFlyweight::operation::extrinsicState = "
+ extrinsicState);
}
}

// 3. UnsharedConcreteFlyweight
public class UnsharedConcreteFlyweight extends Flyweight{
@Override
public void operation(String extrinsicState) {
System.out.println("UnsharedConcreteFlyweight::operation::extrinsicState
= " + extrinsicState);
}
}

// 4. FlyweightFactory
public class FlyweightFactory {
private static HashMap<String, Flyweight> flyweightMaps = new HashMap<>();

public static Flyweight getFlyweight(String key){
if (flyweightMaps.containsKey(key)){
return flyweightMaps.get(key);
}else {
Flyweight flyweight = new ConcreteFlyweight();
flyweightMaps.put(key, flyweight);
return flyweight;
}
}
}

// 5. Test
public class TestFlyweight {
public static void main(String[] args) {
String extrinsicState = "A";
Flyweight flyweight1 = FlyweightFactory.getFlyweight(extrinsicState);
flyweight1.operation(extrinsicState);

extrinsicState = "B";
Flyweight flyweight2 = FlyweightFactory.getFlyweight(extrinsicState);
flyweight2.operation(extrinsicState);

extrinsicState = "C";
Flyweight flyweight3 = new UnsharedConcreteFlyweight();
flyweight3.operation(extrinsicState);
}
}

// 6. Result
ConcreteFlyweight::operation::extrinsicState = A
ConcreteFlyweight::operation::extrinsicState = B
UnsharedConcreteFlyweight::operation::extrinsicState = C

总结

享元模式主要使用了缓存来减少创建重复对象,能大大降低内存占用率。

参考文档

  • 大话设计模式
  • Android 源码设计模式解析与实战