您的位置:首页 > 其它

设计模式之享元模式(Flyweight)

2017-06-30 14:39 513 查看
优点: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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  设计模式 享元