newwy
奋斗在IT路上的小蜗牛。一步一步往上爬,爬到小牛,在到大牛,然后是神牛,然后是犇,然后就可以离开IT行业,回归大自然了。 远离IT,珍爱生命!!! 记录学习的点滴。
/*********************************
*设计模式--享元模式实现
*C++语言
*Author:WangYong
*Blog:http://www.cnblogs.com/newwy
********************************/
#include <iostream>
#include <cassert>
#include <vector>
#include <string>
using namespace std;
class Flyweight
{
	public:
	virtual ~Flyweight(){}
	virtual void Operation(const string & extrinsicState){}
	string GetIntrinsicState(){return this->_intrinsicState;}
	protected:
	Flyweight(string intrinsicState){this->_intrinsicState = _intrinsicState;}
	private:
	string _intrinsicState;
};
class ConcreteFlyweight:public Flyweight
{
	public:
	ConcreteFlyweight(string intrinsicState):Flyweight(intrinsicState)
	{cout<<"ConcreteFlyweight Build ...."<<intrinsicState<<endl;}
	~ConcreteFlyweight(){}
	void Operation(const string & extrinsicState)
	{
		cout<<"ConcreteFlyweight:内蕴"<<this->GetIntrinsicState()
		<<"ConcreteFlyweight:外蕴"<<extrinsicState<<endl;
	}
};
class FlyweightFactory
{
	public:
	FlyweightFactory(){}
	~FlyweightFactory(){}
	Flyweight * GetFlyweight(const string &key)
	{
		vector<Flyweight *>::iterator it = _fly.begin();
		for(;it != _fly.end(); it++)
		{
			if( (*it)->GetIntrinsicState() == key)
				cout<<"already created by users..."<<endl;
			return *it;
		}
		Flyweight *fn = new ConcreteFlyweight(key);
		_fly.push_back(fn);
		return fn;	
	}
	private:
	vector<Flyweight*> _fly;
};
int main()
{
	FlyweightFactory *fc = new FlyweightFactory();
	Flyweight * fw1 = fc->GetFlyweight("hello");
	Flyweight * fw2 = fc->GetFlyweight("world!");
	Flyweight * fw3 = fc->GetFlyweight("hello");
}

posted on 2010-10-18 23:54  newwy  阅读(384)  评论(0编辑  收藏  举报