#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;
}
《大話設計模式》讀書筆記之C++實現--chapter26享元模式
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.