首页 > 代码库 > 享元模式
享元模式
【1】什么是享元模式?
享元模式:
【2】享元模式的代码示例:
代码示例1:
1 #include <iostream> 2 #include <string> 3 #include <map> 4 using namespace std; 5 6 class Flyweight 7 { 8 public: 9 virtual void operation(int) = 0;10 };11 12 class ConcreteFlyweight : public Flyweight13 {14 void operation(int extrinsicState)15 {16 cout << "具体FlyWeight: " << extrinsicState << endl;17 }18 };19 20 class UnsharedConcreteFlyweight : public Flyweight21 {22 void operation(int extrinsicState)23 {24 cout << "不共享的具体FlyWeight: " << extrinsicState << endl; 25 }26 };27 28 class FlyweightFactory29 {30 private:31 map<string,Flyweight*> flyweights;32 public:33 FlyweightFactory()34 {35 flyweights["X"] = new ConcreteFlyweight();36 flyweights["Y"] = new ConcreteFlyweight();37 flyweights["Z"] = new UnsharedConcreteFlyweight();38 }39 Flyweight *getFlyweight(string key)40 {41 return (Flyweight *)flyweights[key];42 }43 };44 45 int main()46 {47 int state = 22;48 FlyweightFactory *f = new FlyweightFactory();49 50 Flyweight *fx = f->getFlyweight("X");51 fx->operation(--state);52 53 Flyweight *fy = f->getFlyweight("Y");54 fy->operation(--state);55 56 Flyweight *fz = f->getFlyweight("Z");57 fz->operation(--state);58 59 Flyweight *uf = new UnsharedConcreteFlyweight();60 uf->operation(--state);61 62 return 0;63 }64 //Result:65 /*66 具体FlyWeight: 2167 具体FlyWeight: 2068 不共享的具体FlyWeight: 1969 不共享的具体FlyWeight: 1870 */
代码示例2:
1 #include <iostream> 2 #include <list> 3 #include <string> 4 #include <map> 5 using namespace std; 6 7 class WebSite 8 { 9 public:10 virtual void use() = 0;11 }; 12 13 class ConcreteWebSite : public WebSite14 {15 private:16 string name;17 public:18 ConcreteWebSite(string name)19 {20 this->name = name;21 }22 void use()23 {24 cout << "网站分类: " << name << endl;25 }26 };27 28 class WebSiteFactory29 {30 private:31 map<string,WebSite*> wf;32 public:33 34 WebSite *getWebSiteCategory(string key)35 {36 if (wf.find(key) == wf.end())37 {38 wf[key] = new ConcreteWebSite(key);39 } 40 return wf[key];41 }42 43 int getWebSiteCount()44 {45 return wf.size();46 }47 };48 49 int main()50 {51 WebSiteFactory *wf = new WebSiteFactory();52 53 WebSite *fx = wf->getWebSiteCategory("good");54 fx->use();55 56 WebSite *fy = wf->getWebSiteCategory("产品展示");57 fy->use();58 59 WebSite *fz = wf->getWebSiteCategory("产品展示");60 fz->use();61 62 63 WebSite *f1 = wf->getWebSiteCategory("博客");64 f1->use();65 66 WebSite *f2 = wf->getWebSiteCategory("微博");67 f2->use();68 69 cout << wf->getWebSiteCount() << endl;70 return 0;71 }72 //Result:73 /*74 网站分类: good75 网站分类: 产品展示76 网站分类: 产品展示77 网站分类: 博客78 网站分类: 微博79 480 */
Good Good Study, Day Day Up.
顺序 选择 循环 总结
享元模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。