FlyWeight模式

原创
2017/05/02 15:00
阅读数 20
//FlyWeight模式 亨元模式
typedef  std::string STATE;
class Flyweight
{
public:
	virtual ~Flyweight(){}
	STATE GetIntrinsicState(){return m_State;}
	virtual void Operation() = 0;

protected:
	Flyweight(const STATE& state):m_State(state){}
protected:
	STATE m_State;
};

class ConcreateFlyweight: public Flyweight
{
public:
	ConcreateFlyweight(const STATE& state): Flyweight(state){}
	~ConcreateFlyweight(){}
	void Operation()
	{
		printf("%s!\n",m_State.c_str());
	}
};

class FlyweightFactory
{
private:
	FlyweightFactory(){}
	~FlyweightFactory();
public:
	static Flyweight* GetFlyweight(const STATE& key);
	static void	ReleaseFlyweight();
private:
	static map<STATE,Flyweight*>  m_mapFlyweight;
};

map<STATE,Flyweight*>  FlyweightFactory::m_mapFlyweight;

void FlyweightFactory::ReleaseFlyweight()
{
	map<STATE,Flyweight*>::iterator it=m_mapFlyweight.begin();
	for (;it!=m_mapFlyweight.end();++it)
	{
		delete(it->second);
	}
	m_mapFlyweight.clear();
}

Flyweight* FlyweightFactory::GetFlyweight(const STATE& key)
{
	map<STATE,Flyweight*>::iterator it;
	it=m_mapFlyweight.find(key);
	if (it!=m_mapFlyweight.end())
	{
		return it->second;
	}
	else
	{
		Flyweight *pFlyweight=new ConcreateFlyweight(key);
		m_mapFlyweight.insert(make_pair(key,pFlyweight));
		return pFlyweight;
	}
}
//FlyWeight模式
int _tmain(int argc, _TCHAR* argv[])
{

	Flyweight* a=FlyweightFactory::GetFlyweight("a");
	a->Operation();
	FlyweightFactory::GetFlyweight("a")->Operation();
	Flyweight* b=FlyweightFactory::GetFlyweight("b");
	b->Operation();
	Flyweight* c=FlyweightFactory::GetFlyweight("c");
	c->Operation();
	Flyweight* d=FlyweightFactory::GetFlyweight("d");
	d->Operation();
	FlyweightFactory::ReleaseFlyweight();
	getchar();
	return 0;
}
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部