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<< " 用户:"<< 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