#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享元模式
最新推荐文章于 2025-04-24 14:42:39 发布