设计模式之享元模式(Flyweight)
2017-06-30 14:39
513 查看
优点:1)大幅度地降低内存中对象的数量
运行结果:
Creating a new Flyweight:hello
Creating a new Flyweight:world
The Flyweight:hello already exists
#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
相关文章推荐
- 设计模式循序渐进(4)享元模式 Flyweight
- 设计模式学习笔记(十二)——Flyweight享元模式
- 设计模式——享元模式(Flyweight)
- 设计模式:Flyweight模式(享元模式)
- 设计模式 Design Parttern ——享元模式FlyWeight
- 重温设计模式(一)——享元模式(Flyweight)
- 设计模式--Flyweight享元模式
- 设计模式学习8 -- Flyweight(享元模式)
- 设计模式 - FlyWeight 模式(享元模式)
- 设计模式学习笔记(十二)——Flyweight享元模式
- 设计模式学习笔记(二十二)—FlyWeight享元模式
- 设计模式--享元模式(Flyweight)
- 设计模式——享元模式(Flyweight)
- 设计模式学习笔记--Flyweight享元模式
- [导入]C#面向对象设计模式纵横谈(12):Flyweight 享元模式(结构型模式).zip(7.86 MB)
- 设计模式—FlyWeight享元模式
- 设计模式--享元模式(Flyweight)
- 一天一个设计模式之享元模式(flyweight)
- 设计模式(十二)之Flyweight - 享元模式
- 设计模式(13)-享元模式(Flyweight)