组合模式
【1】什么是组合模式?
将对象组合成树形结构以表示“部分整体”的层次结构。
组合模式使得用户对单个对象和组合对象的使用具有一致性。
【2】组合模式代码示例:
代码示例:
1 #include <iostream>
2 #include <vector>
3 #include <string>
4 using namespace std;
5
6 class Component
7 {
8 public:
9 string name;
10 Component(string name)
11 {
12 this->name = name;
13 }
14 virtual void add(Component *) = 0;
15 virtual void remove(Component *) = 0;
16 virtual void display(int) = 0;
17 };
18
19 class Leaf : public Component
20 {
21 public:
22 Leaf(string name) : Component(name)
23 {}
24 void add(Component *c)
25 {
26 cout << "leaf cannot add" << endl;
27 }
28 void remove(Component *c)
29 {
30 cout << "leaf cannot remove" << endl;
31 }
32 void display(int depth)
33 {
34 string str(depth, '-');
35 str += name;
36 cout << str << endl;
37 }
38 };
39
40 class Composite : public Component
41 {
42 private:
43 vector<Component*> component;
44 public:
45 Composite(string name) : Component(name)
46 {}
47 void add(Component *c)
48 {
49 component.push_back(c);
50 }
51 void remove(Component *c)
52 {
53 vector<Component*>::iterator iter = component.begin();
54 while (iter != component.end())
55 {
56 if (*iter == c)
57 {
58 component.erase(iter++);
59 }
60 else
61 {
62 iter++;
63 }
64 }
65 }
66 void display(int depth)
67 {
68 string str(depth, '-');
69 str += name;
70 cout << str << endl;
71
72 vector<Component*>::iterator iter=component.begin();
73 while (iter != component.end())
74 {
75 (*iter)->display(depth + 2);
76 iter++;
77 }
78 }
79 };
80
81
82 int main()
83 {
84 Component *p = new Composite("小李");
85 p->add(new Leaf("小王"));
86 p->add(new Leaf("小强"));
87
88 Component *sub = new Composite("小虎");
89 sub->add(new Leaf("小王"));
90 sub->add(new Leaf("小明"));
91 sub->add(new Leaf("小柳"));
92
93 p->add(sub);
94 p->display(0);
95
96 cout << "*******" << endl;
97 sub->display(2);
98
99 return 0;
100 }
101 //Result:
102 /*
103 小李
104 --小王
105 --小强
106 --小虎
107 ----小王
108 ----小明
109 ----小柳
110 *******
111 --小虎
112 ----小王
113 ----小明
114 ----小柳
115 */
Good Good Study, Day Day Up.
顺序 选择 循环 总结