一、UML图
二、介绍
享元模式(英语:Flyweight Pattern)它使用共享物件,用来尽可能减少内存使用量以及分享资讯给尽可能多的相似物件;它适合用于当大量物件只是重复因而导致无法令人接受的使用大量内存。通常物件中的部分状态是可以分享。常见做法是把它们放在外部数据结构,当需要使用时再将它们传递给享元。
三、范例
#include <map> #include <iostream> #include <string> using namespace std; class Flyweight { public: virtual void Operation(int extrinsicstate) = 0; }; class ConcreteFlyweight : public Flyweight { public: void Operation(int extrinsicstate) { cout << "具体Flyweight:" << extrinsicstate << endl; } }; class UnsharedConcreteFlyweight : public Flyweight { public: void Operation(int extrinsicstate) { cout << "不共享的具体Flyweight:" << extrinsicstate << endl; } }; class FlyweightFactory { public: FlyweightFactory() { flys["X"] = new ConcreteFlyweight(); flys["Y"] = new ConcreteFlyweight(); flys["Z"] = new ConcreteFlyweight(); } Flyweight* getFlyweight(string key) { return flys[key]; } private: map<string,Flyweight*> flys; }; int main() { int extr = 11; FlyweightFactory *f = new FlyweightFactory(); Flyweight *fx = f->getFlyweight("X"); fx->Operation(extr); Flyweight *fn = new UnsharedConcreteFlyweight(); fn->Operation(--extr); getchar(); return 0; }
上例的FlyweightFactory可以调整一下
class FlyweightFactory { public: FlyweightFactory() { // flys.insert(make_pair("X",new ConcreteFlyweight())); // flys.insert(make_pair("Y",new ConcreteFlyweight())); // flys.insert(make_pair("Z",new ConcreteFlyweight())); // flys["X"] = new ConcreteFlyweight(); // flys["Y"] = new ConcreteFlyweight(); // flys["Z"] = new ConcreteFlyweight(); } Flyweight* getFlyweight(string key) { if (flys.find(key) == flys.end()) { flys.insert(make_pair(key,new ConcreteFlyweight())); } return flys[key]; } private: map<string,Flyweight*> flys; };