C++実現メタモード

1556 ワード

/*
	    :      ,                 
	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;
}