【设计模式】结构型模式-Composite模式
# 功能
将对象组合成树形结构以表示"部分-整体"的层次结构。
# 解决
- 主要解决:它在我们树型结构的问题中,模糊了简单元素和复杂元素的概念,客户程序可以像处理简单元素一样来处理复杂元素,从而使得客户程序与复杂元素的内部结构解耦。
- 何时使用:
- 您想表示对象的部分-整体层次结构(树形结构)。
- 您希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象。
- 如何解决:树枝和叶子实现统一接口,树枝内部组合该接口
- 关键代码:树枝内部组合该接口,并且含有内部属性 List,里面放 Component。
# 优缺点
- 优点:
- 高层模块调用简单
- 节点自由增加
- 缺点:在使用组合模式时,其叶子和树枝的声明都是实现类,而不是接口,违反了依赖倒置原则
# 应用场景
- 应用实例: 1、算术表达式包括操作数、操作符和另一个操作数,其中,另一个操作符也可以是操作数、操作符和另一个操作数。 2、在 JAVA AWT 和 SWING 中,对于 Button 和 Checkbox 是树叶,Container 是树枝。
- 使用场景:部分、整体场景,如树形菜单,文件、文件夹的管理
- 注意事项:定义时为具体类
# 简单示例代码部分
Composite.h
#ifndef _COMPOSITE_H_
#define _COMPOSITE_H_
#include <vector>
#include <iostream>
using namespace std;
class Component {
public:
Component(){}
virtual ~Component(){}
virtual void Operation() = 0;
virtual void Add(const Component& com){}
virtual void Remove(const Component& com){}
virtual Component* GetChild(int ){
return 0;
}
};
class Leaf:public Component {
public:
Leaf(){}
~Leaf(){}
void Operation(){
cout<<"Leaf operation.....\n";
}
};
class Composite:public Component {
public:
Composite(){}
~Composite(){}
void Operation(){
vector<Component*>::iterator comIter = comVec.begin();
for (;comIter != comVec.end();comIter++) {
(*comIter)->Operation();
}
}
void Add(Component* com){
comVec.push_back(com);
}
void Remove(Component* com){
// comVec.erase(&com);
}
Component* GetChild(int index){
return comVec[index];
}
private:
vector<Component *> comVec;
};
#endif
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
52
53
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
52
53
main.cpp
#include "Composite.h"
#include <iostream>
using namespace std;
int main() {
Leaf* l = new Leaf();
l->Operation();
Composite* com = new Composite();
com->Add(l);
com->Operation();
Component* ll = com->GetChild(0);
ll->Operation();
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
编辑 (opens new window)
上次更新: 2022/05/18, 15:47:37