标签:
享元模式:
使用共享技术有效地支持大量细粒度的对象。
Use sharing to support large numbers of fine-grained objects efficiently.
这个设计模式和它的名字一样核心是为了共享代码。
UML图:
主要包括:
C++代码:
#include <iostream>
#include <map>
using namespace std;
class FlyWeight
{
public:
virtual void operation(int extrinsicState)=0;
};
class ConcreteFlyWeight:public FlyWeight
{
public:
void operation(int extrinsicState)
{
cout<<"ConcreteFlyWeight : "<<extrinsicState<<endl;
}
};
class UnSharedConcreteFlyWeight:public FlyWeight
{
public:
void operation(int extrinsicState)
{
cout<<"UnSharedConcreteFlyWeight : "<<extrinsicState<<endl;
}
};
class FlyWeightFactory
{
public:
FlyWeightFactory()
{
flyWeights["X"]=new ConcreteFlyWeight();
flyWeights["Y"]=new ConcreteFlyWeight();
flyWeights["Z"]=new ConcreteFlyWeight();
}
FlyWeight * getFlyWeight(string key)
{
return flyWeights[key];
}
private:
map<string,FlyWeight *> flyWeights;
};
int main()
{
cout<<"基本享元模式代码"<<endl;
int extrinsicState=22;
FlyWeightFactory *factory=new FlyWeightFactory();
FlyWeight * fx=factory->getFlyWeight("X");
fx->operation(--extrinsicState);
FlyWeight * fy=factory->getFlyWeight("Y");
fy->operation(--extrinsicState);
FlyWeight * fz=factory->getFlyWeight("Z");
fz->operation(--extrinsicState);
FlyWeight * fu=new UnSharedConcreteFlyWeight();
fu->operation(--extrinsicState);
delete factory;
delete fx;
delete fy;
delete fz;
delete fu;
return 0;
}
执行输出:
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/u012501459/article/details/46692469