适用情境:把操作简单对象和复杂对象的接口统一,使得客户端使用组合对象和简单对象的方式一致.
// component.h
#ifndef COMPONENT_H
#define COMPONENT_H
#include <string>
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 <vector>
#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<Component*> m_components;
};
#endif // COMPOSITE_H
// composite.cpp
#include <iostream>
#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<Component*>::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 <iostream>
#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 <iostream>
#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;
}