享元模式
【1】什么是享元模式? 享元模式: 【2】享元模式的代码示例:
#include <iostream> #include <string> #include <map> using namespace std; class Flyweight { public: virtual void operation(int) = 0; }; class ConcreteFlyweight : public Flyweight { void operation(int extrinsicState) { cout << "具体FlyWeight: " << extrinsicState << endl; } }; class UnsharedConcreteFlyweight : public Flyweight { void operation(int extrinsicState) { cout << "不共享的具体FlyWeight: " << extrinsicState << endl; } }; class FlyweightFactory { private: map<string,Flyweight*> flyweights; public: FlyweightFactory() { flyweights["X"] = new ConcreteFlyweight(); flyweights["Y"] = new ConcreteFlyweight(); flyweights["Z"] = new UnsharedConcreteFlyweight(); } Flyweight *getFlyweight(string key) { return (Flyweight *)flyweights[key]; } }; int main() { int state = 22; FlyweightFactory *f = new FlyweightFactory(); Flyweight *fx = f->getFlyweight("X"); fx->operation(--state); Flyweight *fy = f->getFlyweight("Y"); fy->operation(--state); Flyweight *fz = f->getFlyweight("Z"); fz->operation(--state); Flyweight *uf = new UnsharedConcreteFlyweight(); uf->operation(--state); return 0; } //Result: /* 具体FlyWeight: 21 具体FlyWeight: 20 不共享的具体FlyWeight: 19 不共享的具体FlyWeight: 18 */
代码示例2:
#include <iostream> #include <list> #include <string> #include <map> using namespace std; class WebSite { public: virtual void use() = 0; }; class ConcreteWebSite : public WebSite { private: string name; public: ConcreteWebSite(string name) { this->name = name; } void use() { cout << "网站分类: " << name << endl; } }; class WebSiteFactory { private: map<string,WebSite*> wf; public: WebSite *getWebSiteCategory(string key) { if (wf.find(key) == wf.end()) { wf[key] = new ConcreteWebSite(key); } return wf[key]; } int getWebSiteCount() { return wf.size(); } }; int main() { WebSiteFactory *wf = new WebSiteFactory(); WebSite *fx = wf->getWebSiteCategory("good"); fx->use(); WebSite *fy = wf->getWebSiteCategory("产品展示"); fy->use(); WebSite *fz = wf->getWebSiteCategory("产品展示"); fz->use(); WebSite *f1 = wf->getWebSiteCategory("博客"); f1->use(); WebSite *f2 = wf->getWebSiteCategory("微博"); f2->use(); cout << wf->getWebSiteCount() << endl; return 0; } //Result: /* 网站分类: good 网站分类: 产品展示 网站分类: 产品展示 网站分类: 博客 网站分类: 微博 4 */
http://www.cnblogs.com/Braveliu/p/3956948.html