[设计模式] 组合模式(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;
 1class Component { // 为组合中的对象声明接口,在适当情况下,实现所有类共有接口的默认行为
 2protected:
 3    string name;
 4public:
 5    Component(string n) { name = n; }
 6    virtual ~Component() {}
 7    virtual void Add(Component* c) = 0;
 8    virtual void Remove(Component* c) = 0;
 9    virtual void Display(int depth) = 0;
10};
1class Leaf : public Component { // 在组合中表示叶节点对象叶节点没有子节点
2public:
3    Leaf(string name) : Component(name) {}
4    void Add(Component* c){} // 叶节点没有Add功能但这样做能使接口具备一致性这就是透明方式如果不加入Add和Remove方法那就是安全方式
5    void Remove(Component* c){} // 同上
6    void Display(int depth) { cout << name << "  " << depth << endl; }
7};
 1class Composite : public Component { // 定义有枝节点行为用来存储子部件
 2private:
 3    list<Component* > children;
 4public:
 5    Composite(string name) : Component(name) {}
 6    void Add(Component* c) { children.push_back(c); }
 7    void Remove(Component* c) { children.remove(c); }
 8    void Display(int depth) {
 9        cout << name << "  " << depth << endl;
10        for (auto c = children.begin(); c != children.end(); c++) {
11            (*c)->Display(depth+1);
12        }
13    }
14};
1int main() { // 客户端实现代码
2    Composite* root = new Composite("root");
3    root->Add(new Leaf("Leaf A"));
4    root->Add(new Leaf("Leaf B"));
1    Composite* comp = new Composite("Composite X");
2    comp->Add(new Leaf("Leaf XA"));
3    comp->Add(new Leaf("Leaf XB"));
4    root->Add(comp);
1    Composite* comp2 = new Composite("Composite XY");
2    comp2->Add(new Leaf("Leaf XYA"));
3    comp2->Add(new Leaf("Leaf XYB"));
4    comp->Add(comp2);
    root->Display(1);

    return 0;
}

最后打印的结果为:

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