运行共享技术有效地支持大量细粒度的对象。 ——《设计模式》GoF
假设要设计一个字处理系统,如果每一个字符都是对象,一篇文章将会有太多对象了 但将这些字符按照字体分类,那么仅会有几种字体对象
//该模式解决的不是抽象问题而是性能问题 class Font { private: //unique object key string key; //object state //.... public: Font(const string& key) { //... } }; ß class FontFactory//字体工厂 { private: map<string,Font* > fontPool;//维护字体对象池 public: Font* GetFont(const string& key) { map<string,Font*>::iterator item=fontPool.find(key); if(item!=footPool.end())//之前创建过该对象 { return fontPool[key];//有返回 } else//没有创建过 { Font* font = new Font(key); fontPool[key]= font;//添加到字体对象池 return font;//没有添加后再返回 } } void clear() { //... } };
#include <iostream> #include <map> #include <string> using namespace std; class Flyweight { public: virtual void Operation(int extrinsicstate) = 0; virtual ~Flyweight() {} }; class ConcreteFlyweight : public Flyweight { public: void Operation(int extrinsicstate) { cout << "ConcreteFlyweight: " << extrinsicstate << endl; } }; class UnsharedConcreteFlyweight : public Flyweight { // 不强制共享对象,但也可以共享 public: void Operation(int extrinsicstate) { cout << "UnsharedConcreteFlyweight: " << extrinsicstate << endl; } }; class FlyweightFactory { private: map<string, Flyweight*> flyweights; public: Flyweight* GetFlyweight(string key) { if (flyweights[key] == NULL) flyweights[key] = new ConcreteFlyweight(); return (Flyweight*)flyweights[key]; } }; int main() { int extrinsicstate = 22; // 外部状态 FlyweightFactory* f = new FlyweightFactory(); Flyweight* fx = f->GetFlyweight("X"); // X、Y、Z为内部状态 fx->Operation(--extrinsicstate); // ConcreteFlyweight: 21 Flyweight* fy = f->GetFlyweight("Y"); fy->Operation(--extrinsicstate); // ConcreteFlyweight: 20 Flyweight* fz = f->GetFlyweight("Z"); // ConcreteFlyweight: 19 fz->Operation(--extrinsicstate); UnsharedConcreteFlyweight* uf = new UnsharedConcreteFlyweight(); uf->Operation(--extrinsicstate); // UnsharedConcreteFlyweight: 18 delete fx; delete fy; delete fz; delete f; delete uf; return 0; }
享元模式可以避免大量非常相似的开销。在程序设计中,有时需要生成大量细粒度的类实例来表示数据。如果能发现这些实例除了几个参数外基本上都是相同的,有时就能够大幅度地减少需要实例化的类的数量。如果能把那些参数移到类实例的外面,在方法调用时将它们传递进来,就可以通过共享大幅度地减少单个实例的数目。
设计一个字处理系统,如果每一个字符都是对象,一篇文章将会有太多对象了 但将这些字符按照字体分类,那么仅会有几个字体对象
C++设计模式——享元模式Flyweight-Pattern
原文:https://www.cnblogs.com/wkfvawl/p/12532140.html