设计模式 之 《组合模式》

 

GOOD:整体和部分可以被一致对待(如WORD中复制一个文字、一段文字、一篇文章都是一样的操作)

 

 

 

#ifndef __COMPOSITE_MODEL__
#define __COMPOSITE_MODEL__ 

#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Component
{
public:
    string m_strName;
    Component(string strName)
    {
        m_strName = strName;
    }

    virtual void add(Component* com) = 0;
    virtual void display(int nDepth) = 0;
};

class Leaf : public Component
{
public:
    Leaf(string strName) : Component(strName){}
    virtual void add(Component* com)
    {
        cout<<"leaf can't add"<<endl;
    }
    virtual void display(int nDepth)
    {
        string strtemp;
        for (int i=0; i<nDepth; ++i)
        {
            strtemp += "-";
        }
        strtemp += m_strName;
        cout<<strtemp<<endl;
    }
};

class Composite : public Component
{
private:
    vector<Component*> m_component;
public:
    Composite(string strName) : Component(strName) {}
    virtual void add(Component* com)
    {
        m_component.push_back(com);
    }

    virtual void display(int nDepth)
    {
        string strtemp;
        for(int i=0; i<nDepth; ++i)
        {
            strtemp += "-";
        }
        strtemp += m_strName;
        cout<<strtemp<<endl;

        vector<Component*>::iterator iter = m_component.begin();
        while(iter!=m_component.end())
        {
            (*iter)->display(nDepth+2);
            iter++;
        }
    }
};

#endif //__COMPOSITE_MODEL__

/*
#include "CompositeModel.h"
int _tmain(int argc, _TCHAR* argv[])
{
Composite* p = new Composite("小王");
p->add(new Leaf("小李"));
p->add(new Leaf("小赵"));

Composite* p1 = new Composite("小小五");
p1->add(new Leaf("大三"));

p->add(p1);
p->display(1);

return 0;
}
*/

 

 

原文地址:https://www.cnblogs.com/MrGreen/p/3420529.html