初学设计模式之享元模式

孤街醉人 提交于 2019-11-29 17:33:37
 1 /*利用享元模式买衬衫的程序案例
 2 需求:1、库存无某种颜色衬衫时,需要对该颜色衬衫进行进货(列表中无该属性的对象时,新建立该属性对象,再调用)
 3       2、库存中有该对象时,直接售卖不用进货(列表中有该属性的对象时,直接调用)
 4 程序注解:库存使用map实现的
 5           售卖等行为是用cout<<相应的话语模拟实现的
 6 */
 7 #include<iostream>
 8 #include<string>
 9 #include<map>
10 using namespace std;
11 
12 //抽象享元类
13 class FlyWeight
14 {
15 public:
16     void sail()
17     {
18 
19     };
20 };
21 
22 //具体的享元类
23 class ConcreteFlyWeight:public FlyWeight
24 {
25 public:
26     ConcreteFlyWeight(string color)
27     {
28         shirtColor = color;
29         cout<<"新入库衬衫颜色"<<shirtColor<<endl;
30     };
31     void sail()
32     {
33         cout<<"卖掉衬衫颜色为"<<shirtColor<<endl<<endl;
34     };
35 private:
36     string shirtColor;
37 };
38 
39 //工厂类
40 class Factory
41 {
42 public:
43     ConcreteFlyWeight* factory(string color)
44     {
45         
46         map<string, ConcreteFlyWeight*>::iterator iter = SHIRT_MAP.find(color);
47         if (iter!= SHIRT_MAP.end())
48         {   
49             cout<<"库存有货"<<endl;
50             ConcreteFlyWeight *it = SHIRT_MAP[color];
51             return it;
52         }
53         else
54         {   cout<<"库存无货"<<endl;
55             ConcreteFlyWeight *m_Color=new ConcreteFlyWeight(color);
56             SHIRT_MAP.insert(map<string, ConcreteFlyWeight*>::value_type(color,m_Color));
57             ConcreteFlyWeight *it = SHIRT_MAP[color];
58             return it;
59         }
60         
61     }
62 private:
63     map<string, ConcreteFlyWeight*>SHIRT_MAP;
64 };
65 
66 //主函数
67 int main()
68 {
69     Factory m_factory;
70 
71     cout<<"1号顾客买红色衬衫"<<endl;
72     ConcreteFlyWeight *m_ConcreteFlyWeight1=m_factory.factory("Red");
73     m_ConcreteFlyWeight1->sail();
74 
75     cout<<"2号顾客买蓝色衬衫"<<endl;
76     ConcreteFlyWeight *m_ConcreteFlyWeight2=m_factory.factory("Blue");
77     m_ConcreteFlyWeight2->sail();
78 
79     cout<<"3号顾客买红色衬衫"<<endl;
80     ConcreteFlyWeight *m_ConcreteFlyWeight3=m_factory.factory("Red");
81     m_ConcreteFlyWeight3->sail();
82 
83     getchar();//停留输出界面,按任意键结束
84     return 0;
85 }

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!