问题:
我们想对所有动物进行管理,每种动物对应一个类,他们都是继承自animal。如果我们对每一个动物都生成一个实例,那么这数量是非常庞大了,我们需要想一个比较不错的方法
解决方案:
我们可以为每一类动物建立一个对象,让这个对象持有这类动物的固定属性,对于需要变化的因素,我们可以通过参数传进来,进行处理;这样我们就不必创建大量的对象;这就死FlyWeight模式;
源代码:
#include <iostream>
#include <VECTOR>
#include <STRING>
using namespace std;
class FlyWeight{
public:
virtual ~FlyWeight(){}
virtual void Operator(const string& str)=0;
string GetIntrinsicState(){return intrinsicState;}
protected:
FlyWeight(const string &key){this->intrinsicState=key;};//只声明,不实现,则客户端永远不能实例化
private:
string intrinsicState;
};
class ConcreateFlyWeight:public FlyWeight{
public:
ConcreateFlyWeight(const string &key):FlyWeight(key){cout<<"内部对象:"<<GetIntrinsicState()<<"被创建"<<endl;}
virtual ~ConcreateFlyWeight(){}
virtual void Operator(const string &extrinsic)
{
cout<<"外部状态:"<<extrinsic<<endl;;
}
};
class FlyWeightFactory
{
public:
FlyWeightFactory(){}
~FlyWeightFactory(){}
FlyWeight *GetFlyWeight(const string&key)
{
vector<FlyWeight*>::iterator ite=flyWeight.begin();
while(ite!=flyWeight.end())
{
if ((*ite)->GetIntrinsicState()==key)//找到了就返回
{
return (*ite);
}
ite++;
}
FlyWeight *fw=new ConcreateFlyWeight(key);//找不到,就创建一个返回
flyWeight.push_back(fw);
return fw;
}
private:
vector<FlyWeight*> flyWeight;
};
void main()
{
FlyWeightFactory *factory=new FlyWeightFactory();
FlyWeight *f1=factory->GetFlyWeight("say");
FlyWeight *f2=factory->GetFlyWeight("hello");
FlyWeight *f3=factory->GetFlyWeight("say");
f1->Operator("byebye");
f2->Operator("byebye");
f3->Operator("byebye");
}