跳过正文
  1. Posts/

[设计模式] 组合模式(composite) 学习笔记

目的是忽略单一对象和组合对象的不同。 有点像以前写过的用链表定义一个树结构,每个节点是一个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

相关文章

Eigen: C++开源矩阵学习笔记

·2 分钟
接触Eigen的原因是最近在看caffe/caffe2源码,caffe2中使用了Eigen库. Eigen 是一个基于C++模板的线性代数库,直接将库下载后放在项目目录下,然后包含头文件就能使用,非常方便。对于Linux用户,只需要把头文件放到/usr/include 下即可此外,Eigen的接口清晰,稳定高效。

qt 5.x 初探 (5) 

·1 分钟
qt_5.9_ui_doc 还是比直接写代码方便点。。。所以不妨学习一个! 以及。。。qt在2017年6月1号发布了5.9。。。所以之前是5.8。。。现在变成5.9了。。。

qt 5.x初探 (3)

·2 分钟
update3: 终于知道了正确的学习姿势… 用百度把要用的东西大概描述出来,然后总能找到一个是你要的。。。

qt 5.x 学习笔记 (2)

·7 分钟
先来放一波过程中用到的资料和官方文档好了。 basic layout_qt5.8 QBoxLayout Class_qt5.8 QString Class 5.8 QChar Class qt 5.8