设计模式-组合模式

适用情境:把操作简单对象和复杂对象的接口统一,使得客户端使用组合对象和简单对象的方式一致.

设计模式-组合模式_第1张图片

// component.h
#ifndef COMPONENT_H
#define COMPONENT_H

#include 

class Component
{
public:
    Component(std::string strName);
    virtual void Add(Component* com) = 0;
    virtual void Display(int nDepth) = 0;
public:
    std::string m_strName;
};

#endif // COMPONENT_H
// component.cpp
#include "component.h"

Component::Component(std::string strName)
{
    m_strName = strName;
}
// composite.h
#ifndef COMPOSITE_H
#define COMPOSITE_H

#include 
#include "component.h"

class Composite :public Component
{
public:
    Composite(std::string strName);
    virtual void Add(Component *com);
    virtual void Display(int nDepth);
private:
    std::vector m_components;
};

#endif // COMPOSITE_H
// composite.cpp
#include 
#include "composite.h"


Composite::Composite(std::__cxx11::string strName) : Component(strName)
{

}

void Composite::Add(Component *com)
{
    m_components.push_back(com);
}

void Composite::Display(int nDepth)
{
    std::string strTmp;
    for(int i = 0; i < nDepth; i++)
    {
        strTmp += "-";
    }
    strTmp += m_strName;
    std::cout << strTmp << std::endl;
    std::vector::iterator it = m_components.begin();
    while( it != m_components.end())
    {
        (*it)->Display(nDepth + 2);
        it++;
    }
}
// leaf.h
#ifndef LEAF_H
#define LEAF_H

#include "component.h"

class Leaf : public Component
{
public:
    Leaf(std::string strName);
    virtual void Add(Component *com);
    virtual void Display(int nDepth);
};

#endif // LEAF_H
// leaf.cpp
#include 
#include "leaf.h"

Leaf::Leaf(std::__cxx11::string strName) : Component(strName){}

void Leaf::Add(Component *com)
{
    std::cout << "leaf can't add" << std::endl;
}

void Leaf::Display(int nDepth)
{
    std::string strTmp;
    for(int i = 0; i < nDepth; i++)
    {
        strTmp += "-";
    }
    strTmp += m_strName;
    std::cout << strTmp << std::endl;
}

客户端:

// main.cpp
#include 
#include "component.h"
#include "composite.h"
#include "leaf.h"

using namespace std;

int main(int argc, char *argv[])
{
    Composite* p = new Composite("com1");
    p->Add(new Leaf("leaf1"));
    p->Add(new Leaf("leaf2"));

    Composite* p2 = new Composite("com2");
    p2->Add(new Leaf("leaf3"));

    p->Add(p2);
    p->Display(1);
    return 0;
}

你可能感兴趣的:(设计模式,c++)