C++实现享元模式
2012-11-20 18:45
162 查看
/* 享元模式:运用共享技术,有效的实现支持大量细粒度对象的复用 Created by Phoenix_FuliMa */ #include <iostream> #include <string> #include <map> using namespace std; static int objnum = 0; class FlyWeight { public: virtual void Operate(string outer) = 0; }; class ConcreteFlyWeight:public FlyWeight { private: string name; public: ConcreteFlyWeight(string name) :name(name) { objnum++; cout<<"Construct ....."<<endl; } void Operate(string outer) { cout<<"concrete flyweight is operating "<<outer<<endl; } }; class FlyWeightFactory { private: map<string, FlyWeight*> _objects; public: FlyWeight* GetFlyWeight(string name) { map<string, FlyWeight*>::iterator iter; iter = _objects.find(name); if(iter == _objects.end()) { FlyWeight* _tmp = new ConcreteFlyWeight(name); _objects[name] = _tmp; return _tmp; } else { return iter->second; } } ~FlyWeightFactory() { map<string, FlyWeight*>::iterator iter = _objects.begin(); for(; iter != _objects.end(); iter++) { delete iter->second; } } }; int main() { FlyWeightFactory *factory = new FlyWeightFactory(); FlyWeight* test1 = factory->GetFlyWeight("test1"); test1->Operate("funny"); FlyWeight* test2 = factory->GetFlyWeight("test1"); test2->Operate("not funny"); cout<<"number of instance is "<<objnum<<endl; delete factory; system("pause"); return 0; }
相关文章推荐
- 设计模式之享元模式,C++实现
- 设计模式C++实现(9)——享元模式
- 设计模式C++实现(9)——享元模式
- 设计模式C++实现(9)——享元模式
- 设计模式C++实现(9)——享元模式
- 大话设计模式--享元模式 Flyweight -- C++实现实例
- 设计模式C++实现(9)——享元模式
- 设计模式C++实现(9)——享元模式
- 设计模式C++实现(9)——享元模式
- 设计模式C++实现(9)——享元模式
- 大话设计模式--享元模式 Flyweight -- C++实现实例
- 设计模式C++实现(9)——享元模式
- 设计模式C++实现(9)——享元模式
- 设计模式C++实现(9)——享元模式
- 设计模式---享元模式(C++实现)
- 我所理解的设计模式(C++实现)——享元模式(Flyweight Pattern)
- 享元模式之C++实现
- 享元模式及C++实现
- 享元模式C++实现
- 设计模式C++实现(9)——享元模式