享元模式
在软件系统采用对象方案解决问题在于大量细粒度的对象会充斥整个系统。而对象也有一定的开销。
享元模式:运用共享技术有效地支持大量细粒度的对象。
#include<iostream>
#include<string>
#include<map>
using namespace std;
class Font {
private:
string key;
public:
Font(const string& str):key(str){}
void operation() {
cout << "flyweight operate...." << key << endl;
}
};
class FontFactory {
private:
map<string, Font*> fontPool;//对象池
public:
Font* GetFont(const string& key) {
map<string, Font*>::iterator item = fontPool.find(key);
if (item != fontPool.end())
return fontPool[key];
else{
Font* font = new Font(key);
cout << "create a new object!" << endl;
fontPool[key] = font;
return font;
}
}
};
int main()
{
FontFactory* factory = new FontFactory();
Font* font = factory->GetFont("hello");
font->operation();
//第二次执行时,无需再创建新的对象,直接使用对象池的对象
factory->GetFont("hello")->operation();
return 0;
}
结果如下:
要点:
享元模式主要是解决面向对象的代价问题,不解决抽象性问题。即保存创建好的对象,不重复创建相同的对象,节省内存开销。