C++设计模式之十一:Flyweight(享元)

时间:2022-03-28 14:15:40

一、意图:

运用共享技术有效地支持大量细粒度的对象;

二、类图:

C++设计模式之十一:Flyweight(享元)

三、组成元素:

Flyweight:接受并作用于外部状态的接口;

ConcreteFlyweight:实现Flyweight,并为内部状态提供存储空间,这个对象必须是可以共享的;

UnshareConcreteFlyweight:不可共享的对象;

FlyweightFactory:创建并管理flyweight对象;

四、实现代码:

#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;
};
void main()
{
FlyweightFactory *fc = new FlyweightFactory();
Flyweight * fw1 = fc->GetFlyweight("hello");
Flyweight * fw2 = fc->GetFlyweight("world!");
Flyweight * fw3 = fc->GetFlyweight("hello");
}