设计模式-组合模式

shienh 2020年01月28日 249次浏览

组合(Composite)模式的定义:有时又叫作部分-整体模式,它是一种将对象组合成树状的层次结构的模式,用来表示“部分-整体”的关系,使用户对单个对象和组合对象具有一致的访问性。

#include <iostream>
#include <list>
using namespace std;

class Component{
public:
    virtual void process()=0;
};

//树节点
class Composite:public Component{
public:
    Composite(const string& s):name(s){}
    void add(Component* element){
        elements.push_back(element);
    }

    void remove(Component* element){
        elements.remove(element);
    }

    void process(){
        //1.process current node
        cout<<"Composite process"<<endl;

        //2.process leaf node1
        for(auto& e:elements){
           e->process();//多态
        }
    }
private:
    string name;
    list<Component*>elements;

};

//叶子节点
class Leaf:public Component{
public:
    Leaf(string s):name(s){}
    void process(){
        cout<<"leaf process"<<endl;
    }
private:
    string name;
};

int main(int argc, char *argv[])
{
    Composite root("root");
    Composite treenode1("node1");
    Composite treenode2("node2");
    Composite treenode3("node3");
    Composite treenode4("node4");
    Leaf leaf1("leaf1");
    Leaf leaf2("leaf2");

    root.add(&treenode1);
    treenode1.add(&treenode2);
    treenode2.add(&treenode3);
    treenode3.add(&treenode4);
    treenode4.add(&leaf1);
    treenode3.add(&leaf2);
    cout<<"begin root process..."<<endl;
    root.process();
    cout<<"end root process..."<<endl<<endl;

    cout<<"begin treenode2 process..."<<endl;
    treenode2.process();
    cout<<"end treenode2 process..."<<endl;

    return 0;
}