享元(Flyweight)模式的定义:运用共享技术来有効地支持大量细粒度对象的复用。它通过共享已经存在的又橡来大幅度减少需要创建的对象数量、避免大量相似类的开销,从而提高系统资源的利用率。
#include <QCoreApplication>
#include <iostream>
#include <map>
using namespace std;
class Font{
public:
Font(const string& key){
this->key = key;
}
private:
string key;
};
class FontFactory{
public:
//同一种key,只有一个font对象
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<<"new font:"<<key<<endl;
fontPool[key]=font;
return font;
}
}
private:
//字体池
map<string,Font*> fontPool;
};
;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
FontFactory* font = new FontFactory;
font->getFont("10");
font->getFont("10");
font->getFont("11");
return a.exec();
}