享元模式(Flyweight Pattern)主要用于减少创建对象的数量,以减少内存占用和提高性能。这种类型的设计模式属于结构型模式,它提供了减少对象数量从而改善应用所需的对象结构的方式。
享元模式尝试重用现有的同类对象,如果未找到匹配的对象,则创建新对象。使用该模式的关键是将享元的内蕴状态(可以共享)即外蕴状态(不可以共享)区分开来。
优点:大大减少对象的创建,降低系统的内存,使效率提高,且使用享元技术可以有效地支持大量细粒度的对象。
缺点:提高了系统的复杂度,需要分离出外部状态和内部状态,而且外部状态具有固有化的性质,不应该随着内部状态的变化而变化,否则会造成系统的混乱。
类图如下:
示例代码如下:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/* 抽象享元基类 */
class Flyweight {
public:
Flyweight(string state):_state(state) {
}
virtual void Operation(const string&state) { }
string GetState()const { return _state; }
virtual ~Flyweight() { }
private:
string _state;
};
/* 具体享元子类 */
class ConcreteFlyweight :public Flyweight {
public:
ConcreteFlyweight(string state)
:Flyweight(state) {
cout << "ConcreteFlyweight Build..." << state << endl;
}
void Operation(const string& state) {
cout << "ConcreteFlyweight " << GetState() << " \\ " << state << endl;
}
};
/* 具体工厂类,对享元对象进行统一管理 */
class FlyweightFactory {
public:
/* 根据外蕴状态key,需要满足条件的享元对象,找到则返回,没有找到则新建 */
Flyweight *GetFlyweight(std::string key)
{
for (auto fly : _flys)
{
if (fly->GetState() == key)
{
cout << "already created by users..." << endl;
return fly;
}
}
Flyweight *fn = new ConcreteFlyweight(key);
_flys.push_back(fn);
return fn;
}
private:
std::vector<Flyweight*> _flys;
};
int main() {
FlyweightFactory *fc = new FlyweightFactory();
/* 第一次获取hello,不存在,则新建 */
Flyweight *fw1 = fc->GetFlyweight("hello");
/* 第一次获取world,不存在,则新建 */
Flyweight *fw2 = fc->GetFlyweight("world");
/* 第二次获取hello,存在,则返回老对象 */
Flyweight *fw3 = fc->GetFlyweight("hello");
cout <<"fw1: "<< fw1 << endl;
cout << "fw2: " << fw2 << endl;
cout << "fw3: " << fw3 << endl;
delete fw1;
delete fw2;
//delete fw3;
delete fc;
return 0;
}
运行结果如下: