Skip to content

Commit c325689

Browse files
committed
Composite 组合模式
1 parent 0bad16b commit c325689

2 files changed

Lines changed: 105 additions & 1 deletion

File tree

src/18CompositePattern.h

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
//Composite(组合模式-对象结构型)
2+
//将对象组合成树形结构以表示“部分-整体”的层次结构。
3+
//Composite使得用户对单个对象和组合对象的使用具有一致性。
4+
#include <iostream>
5+
#include <list>
6+
7+
//书中定义了Leaf功能节点和Composite容器节点,
8+
//在有的资料上Leaf和Composite接口融合的叫透明组合模式,
9+
//Leaf和Composite一样也有增删接口但没有内部实现;
10+
//只在Composite有子节点管理接口的叫安全组合模式。
11+
12+
//基类
13+
class Component
14+
{
15+
public:
16+
explicit Component(Component* parent = nullptr)
17+
: parentPtr(parent) {
18+
}
19+
virtual ~Component() {}
20+
21+
Component* parent() const {
22+
return parentPtr;
23+
}
24+
25+
void setParent(Component* parent) {
26+
parentPtr = parent;
27+
}
28+
29+
virtual void add(Component* sub) {}
30+
virtual void remove(Component* sub) {}
31+
//一致性的操作接口
32+
virtual void doing() = 0;
33+
34+
private:
35+
Component* parentPtr;
36+
};
37+
38+
class Composite : public Component
39+
{
40+
public:
41+
using Component::Component;
42+
//析构时释放对象树上的子节点
43+
~Composite() {
44+
for (auto&& child : childrenList)
45+
{
46+
delete child;
47+
}
48+
childrenList.clear();
49+
}
50+
51+
void add(Component* child) override {
52+
if (!child) return;
53+
child->setParent(this);
54+
childrenList.push_back(child);
55+
}
56+
void remove(Component* child) override {
57+
if (!child) return;
58+
child->setParent(nullptr);
59+
childrenList.remove(child);
60+
}
61+
void doing() override {
62+
std::cout << "composite doing. for children..." << std::endl;
63+
for (auto&& child : childrenList)
64+
{
65+
child->doing();
66+
}
67+
}
68+
69+
private:
70+
std::list<Component*> childrenList;
71+
};
72+
73+
class Leaf : public Component
74+
{
75+
public:
76+
using Component::Component;
77+
void doing() override {
78+
std::cout << "leaf doing." << std::endl;
79+
}
80+
};
81+
82+
83+
//测试
84+
void testCompositePattern()
85+
{
86+
//如果leaf和composite合二为一,就可以把children管理放到基类了
87+
Composite* c01 = new Composite;
88+
Leaf* l01 = new Leaf;
89+
Leaf* l02 = new Leaf;
90+
c01->add(l01);
91+
c01->add(l02);
92+
93+
Composite* c11 = new Composite;
94+
Leaf* l11 = new Leaf;
95+
Leaf* l12 = new Leaf;
96+
c11->add(l11);
97+
c11->add(l12);
98+
99+
c01->add(c11);
100+
c01->doing();
101+
delete c01;
102+
}

src/main.cpp

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
#include "15MediatorPattern.h"
1717
#include "16StatePattern.h"
1818
#include "17MementoPattern.h"
19+
#include "18CompositePattern.h"
1920

2021
int main()
2122
{
@@ -35,7 +36,8 @@ int main()
3536
//testAdapterPattern();
3637
//testMediatorPattern();
3738
//testStatePattern();
38-
testMementoPattern();
39+
//testMementoPattern();
40+
testCompositePattern();
3941

4042
getchar();
4143
return 0;

0 commit comments

Comments
 (0)