#include <iostream>
#include <string>
#include <map>
using namespace std;
class Flyweight
{
public:
virtual void operation(int)=0;
};
class ConcreteFlyweight:public Flyweight
{
void operation(int extrinsicState)
{
cout<<"具体FlyWeight: "<<extrinsicState<<endl;
}
};
class UnsharedConcreteFlyweight:public Flyweight
{
void operation(int extrinsicState)
{
cout<<"不共享的具体FlyWeight: "<<extrinsicState<<endl;
}
};
class FlyweightFactory
{
private:
map<string,Flyweight*> flyweights;
public:
FlyweightFactory()
{
flyweights["X"]=new ConcreteFlyweight();
flyweights["Y"]=new ConcreteFlyweight();
flyweights["Z"]=new ConcreteFlyweight();
}
Flyweight *getFlyweight(string key)
{
return (Flyweight *)flyweights[key];
}
};
int main()
{
int state=22;
FlyweightFactory *f=new FlyweightFactory();
Flyweight *fx=f->getFlyweight("X");
fx->operation(--state);
Flyweight *fy=f->getFlyweight("Y");
fy->operation(--state);
Flyweight *fz=f->getFlyweight("Z");
fz->operation(--state);
Flyweight *uf=new UnsharedConcreteFlyweight();
uf->operation(--state);
return 0;
}
GOOD:运用共享技术有效地支持大量细粒度的对象(对于 C++来说就是共用一 个内存块啦,对象指针指向同一个地方) 。
如果一个应用程序使用了大量的对象,而这些对象造成了很大的存储开销就应该 考虑使用。还有就是对象的大多数状态可以外部状态,如果删除对象的外部状态,那么可以 用较少的共享对象取代多组对象,此时可以考虑使用享元。