C++实现享元模式

/*
	享元模式:运用共享技术,有效的实现支持大量细粒度对象的复用
	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;
}

你可能感兴趣的:(C++实现享元模式)