23种设计模式--享元模式
结构型设计模式的一种,也叫轻量级模式,故英文名称叫FlyWeight
【DP】定义
运用共享技术有效地支持大量细粒度的对象。
使用场景
- 使用大量的对象,并且这些对象会造成很大的存储开销时需要使用
- 对象大多数状态是外部状态,如果删除外部状态可以使用较少对象来表示,那么可以使用享元模式
类图

该类图的核心是工厂类,工厂类根据少量的内部状态来获取对象,当对象不存在时才创建。这样就能避免对象的创建数量,其实就是我们常说的“把对象缓存起来”。
举例
假设有一个按照模板打印的需求,这个需求的使用场景会是短时间内大量用户来打印。如果不对模板对象的数量进行控制,对内存是巨大的考验。使用享元模式设计如下: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/**
* 模板接口
*/
public interface IPrintTemplate {
void print(User user);
}
/**
* 模板类
*/
public class PrintTemplate implements IPrintTemplate{
// 模板名称(内部状态)
public String name;
public PrintTemplate(String name) {
this.name = name;
}
// user是外部状态
public void print(User user) {
// print with user
}
}
/**
* 用户类
*/
public class User {
private String name;
public User(String name) {
this.name = name;
}
}
/**
* 工厂类
*/
public class Factory {
private Map<String, IPrintTemplate> printTemplateMap = new HashMap<>();
// 核心方法: 获取对象
public IPrintTemplate getPrintTemplate(String name) {
if (!printTemplateMap.contains(name)) {
printTemplateMap.put(name, new PrintTemplate(name));
}
return printTemplateMap.get(name);
}
}
/**
* 客户端类
*/
public class Main {
public static void main() {
Factory factory = new Factory();
IPrintTemplate template1 = factory.getPrintTemplate("模板1");
template1.print(new User("用户1"));
IPrintTemplate template2 = factory.getPrintTemplate("模板1");
template2.print(new User("用户2"));
IPrintTemplate template3 = factory.getPrintTemplate("模板1");
template3.print(new User("用户3"));
}
}
客户端类表示三个不同用户使用同一个查询模板打印,此时只会生成一个模板对象,当模板对象比较占用内存时能极大减少内存消耗。
注意事项
- 类图中的非共享对象是为了表示不是接口的所有实现类都必须共享