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

优点: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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值