优点:1)大幅度地降低内存中对象的数量
#include <iostream>
#include <vector>
using namespace std;
class FlyWeight
{
public:
virtual ~FlyWeight(){}
string getInstrinsicState(){return _state;}
virtual void Operation(string &state) = 0;
protected:
FlyWeight(const string &state){_state = state;}
private:
string _state;
};
class ConcreateFlyweight : public FlyWeight
{
public:
ConcreateFlyweight(const string &state):FlyWeight(state){}
virtual ~ConcreateFlyweight(){}
virtual void Operation(string &state){cout << "ConcreateFlyweight:" << state.data() << endl;}
};
class FlyWeightFactory
{
public:
FlyWeightFactory(){}
~FlyWeightFactory()
{
for(int i = 0; i < _vector.size(); ++i)
delete _vector.at(i);
_vector.clear();
}
FlyWeight *getFlyWeight(const string&key)
{
for(int i = 0; i < _vector.size(); ++i)
{
string state = _vector.at(i)->getInstrinsicState();
if(!strcmp(state.data(),key.data()))
{
cout << "The Flyweight:" << key.data() << " already exists" << endl;
return _vector.at(i);
}
}
std::cout << "Creating a new Flyweight:" << key.data() << std::endl;
FlyWeight *flyWeight = new ConcreateFlyweight(key);
_vector.push_back(flyWeight);
return flyWeight;
}
private:
vector<FlyWeight *> _vector;
};
int main()
{
FlyWeightFactory flyWeightFactory;
FlyWeight *f1 = flyWeightFactory.getFlyWeight("hello");
FlyWeight *f2 = flyWeightFactory.getFlyWeight("world");
flyWeightFactory.getFlyWeight("hello");
return 0;
}
运行结果:
Creating a new Flyweight:hello
Creating a new Flyweight:world
The Flyweight:hello already exists