码迷,mamicode.com
首页 > 编程语言 > 详细

设计模式——享元模式(C++实现)

时间:2017-06-01 00:20:57      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:ret   xxxx   using   string   xxxxx   sign   int   ons   return   

技术分享

 

 1 #include <iostream>
 2 #include <string>
 3 #include <map>
 4 #include <vector>
 5 #include <iterator>
 6 #include <algorithm>
 7 
 8 using namespace std;
 9 
10 class User
11 {
12 public:
13         User(string strName): m_strName(strName)
14         {
15 
16         }
17 
18         string GetName() const
19         {
20                 return m_strName;
21         }
22 
23 private:
24         string m_strName;
25 };
26 
27 class WebSite
28 {
29 public:
30         virtual void Use(const User* stUser) = 0;
31 
32 };
33 
34 class ConcreteWebSite: public WebSite
35 {
36 public:
37         ConcreteWebSite(string strName): m_strName(strName)
38         {
39 
40         }
41 
42         virtual void Use(const User* stUser)
43         {
44                 cout<< "网站分类:"<< m_strName<< "\t 用户:"<< stUser->GetName()<< endl;
45         }
46 
47 private:
48         string m_strName;
49 
50 };
51 
52 class WebSiteFactory
53 {
54 
55 public:
56         WebSite* GetWebSiteCategory(string strKey)
57         {
58                 if (mapFlyWeights.find(strKey) != mapFlyWeights.end())
59                 {
60                         return mapFlyWeights[strKey];
61                 }
62                 else
63                 {
64                         mapFlyWeights.insert(pair<string, WebSite*>(strKey, new ConcreteWebSite(strKey)));
65                         return mapFlyWeights[strKey];
66                 }
67         }
68 
69 private:
70         map<string, WebSite*> mapFlyWeights;
71 };
72 
73 int main(int argc, char* argv[])
74 {
75         WebSiteFactory* f = new WebSiteFactory();
76 
77         WebSite* fx = f->GetWebSiteCategory("产品展示");
78         fx->Use(new User("小菜"));
79 
80 
81         WebSite* fy = f->GetWebSiteCategory("产品展示");
82         fy->Use(new User("大鸟"));
83 
84 
85         WebSite* fz = f->GetWebSiteCategory("博客");
86         fz->Use(new User("xxxxx"));
87 
88 
89         WebSite* fm = f->GetWebSiteCategory("博客");
90         fm->Use(new User("OOOOOO"));
91 
92         return 0;
93 }
94 
95 [root@ ~/learn_code/design_pattern/22_fly_weight]$ ./flyWeight       
96 网站分类:产品展示       用户:小菜
97 网站分类:产品展示       用户:大鸟
98 网站分类:博客   用户:xxxxx
99 网站分类:博客   用户:OOOOOO

 

设计模式——享元模式(C++实现)

标签:ret   xxxx   using   string   xxxxx   sign   int   ons   return   

原文地址:http://www.cnblogs.com/070412-zwc/p/6926356.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!