设计模式-享元模式

享元(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();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值