您的位置:首页 > 编程语言 > C语言/C++

C++实现享元模式

2012-11-20 18:45 162 查看
/*
享元模式:运用共享技术,有效的实现支持大量细粒度对象的复用
Created by Phoenix_FuliMa
*/

#include <iostream>
#include <string>
#include <map>
using namespace std;

static int objnum = 0;

class FlyWeight
{
public:
virtual void Operate(string outer) = 0;
};

class ConcreteFlyWeight:public FlyWeight
{
private:
string name;

public:
ConcreteFlyWeight(string name)
:name(name)
{
objnum++;
cout<<"Construct ....."<<endl;
}
void Operate(string outer)
{
cout<<"concrete flyweight is operating "<<outer<<endl;
}
};

class FlyWeightFactory
{
private:
map<string, FlyWeight*> _objects;

public:

FlyWeight* GetFlyWeight(string name)
{
map<string, FlyWeight*>::iterator iter;
iter = _objects.find(name);
if(iter == _objects.end())
{
FlyWeight* _tmp = new ConcreteFlyWeight(name);
_objects[name] = _tmp;
return _tmp;
}
else
{
return iter->second;
}
}

~FlyWeightFactory()
{
map<string, FlyWeight*>::iterator iter = _objects.begin();
for(; iter != _objects.end(); iter++)
{
delete iter->second;
}
}
};

int main()
{
FlyWeightFactory *factory = new FlyWeightFactory();
FlyWeight* test1 = factory->GetFlyWeight("test1");
test1->Operate("funny");

FlyWeight* test2 = factory->GetFlyWeight("test1");
test2->Operate("not funny");

cout<<"number of instance is "<<objnum<<endl;

delete factory;
system("pause");
return 0;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: