《大话设计模式》读书笔记之C++实现--chapter26享元模式

来源:互联网 发布:hadoop mac 安装 编辑:程序博客网 时间:2024/05/16 16:05
#include <iostream>#include <list>#include <string>#include <map>#include <QDebug>using namespace std;class FlyWeight{public:    virtual void Operation() = 0;    virtual ~FlyWeight(){}};class ConcreteFlyWeight:public FlyWeight{public:    explicit ConcreteFlyWeight(string Id):m_ID(Id){}    void Operation()    {        cout << "ConcreteFlyWeight: " << m_ID <<" Run" << endl;    }private:    string m_ID;};class FlyWeightFactory{public:    FlyWeight* GetFlyWeight(string FlyWeightID)    {        auto iter = m_FlyWeightMap.find(FlyWeightID);        if(iter == m_FlyWeightMap.end())            m_FlyWeightMap.insert(map<string,FlyWeight*>::value_type(FlyWeightID,new ConcreteFlyWeight(FlyWeightID)));        return m_FlyWeightMap[FlyWeightID];    }    int GetFlyWeightCount()    {        return m_FlyWeightMap.size();    }private:    map<string,FlyWeight*> m_FlyWeightMap;};int main(int argc,char** argv){    FlyWeightFactory *flyWeightFactory = new FlyWeightFactory();    FlyWeight* concreteFlyWeight = flyWeightFactory->GetFlyWeight("ConcreteFlyWeight");    FlyWeight* concreteFlyWeight1 = flyWeightFactory->GetFlyWeight("ConcreteFlyWeight1");    FlyWeight* concreteFlyWeight2 = flyWeightFactory->GetFlyWeight("ConcreteFlyWeight1");    concreteFlyWeight->Operation();    concreteFlyWeight1->Operation();    concreteFlyWeight2->Operation();    cout << "flyWeightFactory 拥有的实例个数为:" << flyWeightFactory->GetFlyWeightCount();    return 0;}
阅读全文
0 0
原创粉丝点击