Note: This article is available in Chinese only. 本文暂无英文版本。
View original
目的是忽略单一对象和组合对象的不同。 有点像以前写过的用链表定义一个树结构,每个节点是一个val + 多个tree 。如果某个节点是叶子节点了,那么对应的tree都为NULL. 只不过这里用了更加面向对象的实现。
具体看代码:
1/* ***********************************************
2Author :111qqz
3mail: renkuanze@sensetime.com
4Created Time :2018年08月28日 星期二 14时21分51秒
5File Name :composite.cpp
6************************************************ */
7#include <iostream>
8#include <list>
9#include <string>
10using namespace std;
11
12class Component { // 为组合中的对象声明接口,在适当情况下,实现所有类共有接口的默认行为
13protected:
14 string name;
15public:
16 Component(string n) { name = n; }
17 virtual ~Component() {}
18 virtual void Add(Component* c) = 0;
19 virtual void Remove(Component* c) = 0;
20 virtual void Display(int depth) = 0;
21};
22
23class Leaf : public Component { // 在组合中表示叶节点对象,叶节点没有子节点
24public:
25 Leaf(string name) : Component(name) {}
26 void Add(Component* c){} // 叶节点没有Add功能,但这样做能使接口具备一致性,这就是透明方式,如果不加入Add和Remove方法,那就是安全方式。
27 void Remove(Component* c){} // 同上
28 void Display(int depth) { cout << name << " " << depth << endl; }
29};
30
31class Composite : public Component { // 定义有枝节点行为,用来存储子部件
32private:
33 list<Component* > children;
34public:
35 Composite(string name) : Component(name) {}
36 void Add(Component* c) { children.push_back(c); }
37 void Remove(Component* c) { children.remove(c); }
38 void Display(int depth) {
39 cout << name << " " << depth << endl;
40 for (auto c = children.begin(); c != children.end(); c++) {
41 (*c)->Display(depth+1);
42 }
43 }
44};
45
46int main() { // 客户端实现代码
47 Composite* root = new Composite("root");
48 root->Add(new Leaf("Leaf A"));
49 root->Add(new Leaf("Leaf B"));
50
51 Composite* comp = new Composite("Composite X");
52 comp->Add(new Leaf("Leaf XA"));
53 comp->Add(new Leaf("Leaf XB"));
54 root->Add(comp);
55
56 Composite* comp2 = new Composite("Composite XY");
57 comp2->Add(new Leaf("Leaf XYA"));
58 comp2->Add(new Leaf("Leaf XYB"));
59 comp->Add(comp2);
60
61 root->Display(1);
62
63 return 0;
64}最后打印的结果为:
root 1 Leaf A 2 Leaf B 2 Composite X 2 Leaf XA 3 Leaf XB 3 Composite XY 3 Leaf XYA 4 Leaf XYB 4