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

#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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值