初学设计模式之组合模式

时间:2019-11-10 10:21:46   收藏:0   阅读:96

组合模式的代码例子

 1 #include<iostream>
 2 #include<string>
 3 #include<list>
 4 using namespace std;
 5 
 6 class Component
 7 {
 8 public:
 9     virtual void show(){};
10 
11 };
12 class leaf:public Component
13 {
14 private:
15    string info;
16 
17 public:
18     leaf(string m_info)
19     {
20        info=m_info;
21     };
22     void show()
23     {
24         cout<<info<<endl;
25     };
26 
27 };
28 
29 class ConcreteComponent:public Component
30 {
31 private:
32    string info;
33    list<Component*>m_list;
34 public:
35     ConcreteComponent(string m_info)
36     {
37        info=m_info;
38     };
39     void add(Component* m_ComponentPtr)
40     {
41         m_list.push_back(m_ComponentPtr);
42     };
43     void show()
44     {
45         cout<<info<<endl;
46         list<Component*>::iterator iter=m_list.begin();
47         for (iter;iter!=m_list.end();iter++)
48         {
49             (*iter)->show();
50         }
51     };
52 
53 };
54 
55 int main()
56 {
57     ConcreteComponent m_sum("总部");
58     ConcreteComponent m_com1("分部1");
59     ConcreteComponent m_com2("分部2");
60     leaf m_leaf1("子公司1");
61     leaf m_leaf2("子公司2");
62 
63     m_com1.add(&m_leaf1);
64     m_com1.add(&m_leaf2);
65     m_sum.add(&m_com1);
66     m_sum.add(&m_com2);
67 
68     m_sum.show();
69 
70     getchar();
71     return 0;
72 };

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!