码迷,mamicode.com
首页 > 其他好文 > 详细

初学设计模式之享元模式

时间:2019-09-16 00:27:08      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:col   模拟   out   end   clu   使用   stream   turn   蓝色   

 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 }

 

初学设计模式之享元模式

标签:col   模拟   out   end   clu   使用   stream   turn   蓝色   

原文地址:https://www.cnblogs.com/wuhongjian/p/11524915.html

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