【设计模式】结构型模式-Flyweight模式
# 功能
运用共享技术有效地支持大量细粒度的对象。
# 解决
- 主要解决:有大量对象,可能造成内存溢出
- 何时使用:
- 系统中有大量对象
- 对象消耗大量内存
- 对象的状态大部分可以外部化
- 对象可以按照内蕴状态分为很多组,当把外蕴对象从对象中剔除出来时,每一组对象都可以用一个对象来代替
- 系统不依赖于这些对象身份,这些对象是不可分辨的
- 如何解决:用唯一标识码判断,如果在内存中有,则返回这个唯一标识码所标识的对象
- 关键代码:用 HashMap 存储这些对象
# 优缺点
- 优点:大大减少对象的创建,降低系统的内存,使效率提高
- 缺点:提高了系统的复杂度,需要分离出外部状态和内部状态,而且外部状态具有固有化的性质,不应该随着内部状态的变化而变化,否则会造成系统的混乱
# 应用场景
- 应用实例:
- JAVA 中的 String,如果有则返回,如果没有则创建一个字符串保存在字符串缓存池里面
- 数据库的数据池
- 使用场景:
- 系统有大量相似对象
- 需要缓冲池的场景
- 注意事项:
- 注意划分外部状态和内部状态,否则可能会引起线程安全问题
- 这些类必须有一个工厂对象加以控制
# 简单示例代码部分
Flyweight.hpp
#ifndef _FLYWEIGHT_H_
#define _FLYWEIGHT_H_
#include <iostream>
#include <string>
#include <vector>
#include <cassert>
using namespace std;
class Flyweight {
public:
virtual ~Flyweight(){}
virtual void Operation(const string& extrinsicState){}
string GetIntrinsicState(){
return this->_intrinsicState;
}
protected:
Flyweight(string intrinsicState){
this->_intrinsicState=intrinsicState;
}
private:
string _intrinsicState;
};
class ConcreteFlyweight:public Flyweight {
public:
ConcreteFlyweight(string intrinsicState):Flyweight(intrinsicState){
cout<<"ConcreteFlyweight Build....."<<intrinsicState<<endl;
}
~ConcreteFlyweight(){}
void Operation(const string & extrinsicState){
cout<<"ConcreteFlyweight: 内 蕴 ["<<this->GetIntrinsicState()<<"] 外 蕴 ["<<extrinsicState<<"]"<<endl;
}
};
class FlyweightFactory {
public:
FlyweightFactory(){}
~FlyweightFactory(){}
Flyweight* GetFlyweight(const string& key){
vector<Flyweight*>::iterator it =_fly.begin();
for (; it != _fly.end();it++) {
if ((*it)->GetIntrinsicState() == key) {
cout<<"already created by users...."<<endl;
return *it;
}
}
Flyweight* fn = new ConcreteFlyweight(key);
_fly.push_back(fn);
return fn;
}
private:
vector<Flyweight*> _fly;
};
#endif
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
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
main.cpp
#include "Flyweight.h"
#include <iostream>
using namespace std;
int main() {
FlyweightFactory* fc = new FlyweightFactory();
Flyweight* fw1 = fc->GetFlyweight("hello");
Flyweight* fw2 = fc->GetFlyweight("world!");
Flyweight* fw3 = fc->GetFlyweight("hello");
return 0;
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
编辑 (opens new window)
上次更新: 2022/05/18, 15:47:37