合成模式 Composite

合成模式 , 结构型模式一种 还可以称为部分-整体模式 .
经常会出现有树结构的情况 , 其中由单独的对象或者单独对象组成的合成对象组成 , 此时就需要利用一种方式来完成树结构的构建工作 .
合成模式提供一个树结构中所有对象的统一接口 , 规范树中单独对象和合成对象的构建过程 , 合成模式更像一个数据结构 .
合成模式由抽象构件(Component)、树枝构件(Composite)、树叶(Leaf)构件三部分组成 .
#include <IOSTREAM>
#include <STRING>
#include<vector>
using namespace std;

class Component{
public:
    Component(const string & str):name(str){}
    virtual void add(Component * p) = 0;
    virtual void display(int depth) = 0;
    string name;
};

class Leaf:public Component{
public:
    Leaf(const string & str):Component(str){}
    void add(Component * p){
        cout<<"the leaf cant add a component"<<endl;
    }
    void display(int depth){
        string str;
        int i = 0;
        for( i =0;i<depth;i++){
            str+="    ";
        }
        str+=this->name;
        cout<<str<<endl;
    }
};

class Composite:public Component{
public:
    Composite(const string & str):Component(str){}
    void add(Component * p ){
        m_compsite.push_back(p);
    }
    void display(int depth){           //层级显示,对vector中的成员依次当为Composite调用各自的display
        int i = 0;
        string str;
        for(i = 0;i<depth;i++){
            str+="    ";
        }
        str+=this->name;
        cout<<str<<endl;
        vector<Component *>::iterator it= m_compsite.begin();
        for(;it!=m_compsite.end();it++){
            (*it)->display(depth+1);
        }    
    }

private:
    vector<Component *> m_compsite;
};
int main(int argc, char* argv[])
{
    Composite * p = new Composite("总公司");
    Composite * pchild1 = new Composite("子公司1");
    Composite * pchild2 = new Composite("子公司2");
    Composite * pchild1child = new Composite("子公司1的子公司");
    
    Leaf * pworker = new Leaf("小王");         //最后的叶子,已经不可再add成员了
    pchild1child->add(pworker);
    pchild1->add(pchild1child);
    p->add(pchild1);
    p->add(pchild2);
    p->display(0);
    return 0;
}
原文地址:https://www.cnblogs.com/xiumukediao/p/4636463.html