3 Composite

Davids 2025-08-10 05:12:12
Categories: > > Tags:

组合模式:
客户代码过多依赖于对象内部实现结构(而非接口),对象自身的变化将引起客户代码的频繁修改。
将对象组合成树形结构,以表示“整体-部分”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。
简化树形结构中对象的处理,无论它们是单个对象还是组合对象。
解耦客户端代码与复杂元素的内部结构,使得客户端可以统一处理所有类型的节点。
采用树形结构来实现对象容器,将 一对多 的关系转换为 一对一 的关系。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Abstract {
public:
virtual void DoSomething() = 0;
virtual ~Abstract(){}
};

// 树节点
class Composite : public Abstract {
private:
std::string name;
List<Abstract*> m_Elements;
public:
Composite(const std::string& s) : name(s) {}
virtual void DoSomething() override {
// 无论是什么节点,都是一样的处理方式
for (auto& e : m_Elements)
{
e->DoSomething();
}
}
void AddElement(Abstract* element){ m_Elements.add(element) }
void RemoveElement(Abstract* element){ m_Elements.remove(element) }
};

// 叶子节点
class Leaf : public Abstract {
private:
std::string name;
public:
Leaf(const std::string& s) : name(s) {}
virtual void DoSomething() override {
// do something
}
};

class User {
void Do(Abstract& abstract) {
Composite root("root");
Composite node1("node1");
Composite node2("node2");
Leaf leaf1("leaf1");
Leaf leaf2("leaf2");
root.AddElement(&node1);
node1.AddElement(&node2);
node2.AddElement(&leaf1);
root.AddElement(&leaf2);
// 启动图
root.DoSomething();
}
};