来自于《大话设计模式》
享元模式(Flyweight):
运用共享技术有效地支持大量细粒度的对象。
结构型
UML 类图:
代码实现 C++:
1 #include <iostream>
2 #include <map>
3 #include <string>
4 using namespace std;
5
6 class User
7 {
8 private:
9 string name;
10 public:
11 User(const string& s) : name(s) {}
12 string getName()
13 {
14 return name;
15 }
16 };
17
18 class WebSite
19 {
20 public:
21 WebSite() {}
22 virtual ~WebSite() {}
23 virtual void Use(User* user) = 0;
24 };
25
26 class ConcreteWebSite : public WebSite
27 {
28 private:
29 string name;
30 public:
31 ConcreteWebSite() {}
32 virtual ~ConcreteWebSite() {}
33 ConcreteWebSite(const string& s) : name(s){}
34 virtual void Use(User* user)
35 {
36 cout << "网站分类:" << name << " 用户:" << user->getName() << endl;
37 }
38 };
39
40 class WebSiteFactory
41 {
42 private:
43 map<string, WebSite*> flyweights;
44 public:
45 ~WebSiteFactory()
46 {
47 for (map<string, WebSite*>::iterator iter = flyweights.begin(); iter != flyweights.end(); ++iter)
48 {
49 delete iter->second;
50 }
51 }
52 WebSite* GetWebSiteCategory(const string& key)
53 {
54 map<string, WebSite*>::iterator iter = flyweights.find(key);
55 if (iter != flyweights.end())
56 {
57 return iter->second;
58 }
59 else
60 {
61 flyweights.insert(make_pair(key, new ConcreteWebSite(key)));
62 return flyweights[key];
63 }
64 }
65 int GetWebSiteCount()
66 {
67 return flyweights.size();
68 }
69 };
70
71 int main()
72 {
73 WebSiteFactory* f = new WebSiteFactory;
74 cout << f->GetWebSiteCount() << endl;
75 WebSite* fx = f->GetWebSiteCategory("产品展示");
76 cout << f->GetWebSiteCount() << endl;
77 User* user = new User("小菜");
78 fx->Use(user);
79 delete user;
80
81 WebSite* fy = f->GetWebSiteCategory("产品展示");
82 cout << f->GetWebSiteCount() << endl;
83 user = new User("大鸟");
84 fy->Use(user);
85 delete user;
86
87 WebSite* fz = f->GetWebSiteCategory("产品展示");
88 cout << f->GetWebSiteCount() << endl;
89 user = new User("娇娇");
90 fz->Use(user);
91 delete user;
92
93 WebSite* fl = f->GetWebSiteCategory("博客");
94 cout << f->GetWebSiteCount() << endl;
95 user = new User("老顽童");
96 fl->Use(user);
97 delete user;
98
99 WebSite* fm = f->GetWebSiteCategory("博客");
100 cout << f->GetWebSiteCount() << endl;
101 user = new User("桃谷六仙");
102 fm->Use(user);
103 delete user;
104
105 WebSite* fn = f->GetWebSiteCategory("博客");
106 cout << f->GetWebSiteCount() << endl;
107 user = new User("南海鳄神");
108 fn->Use(user);
109 delete user;
110
111 cout << "网站分类总数为:" << f->GetWebSiteCount() << endl;
112 delete f;
113 return 0;
114 }
posted on 2011-04-30 14:09
unixfy 阅读(235)
评论(0) 编辑 收藏 引用