1.目的
有的需要将对象组织成树形结构,分为枝节点和叶节点,枝节点持有叶节点,同时需要枝节点和叶节点具有相同的行为(对外暴露同样的接口)
2.代码
composite.h
#ifndef COMPOSITE_H_
#define COMPOSITE_H_
#include <list>
#include <string>
#include <iostream>
using namespace std;
class Component
{
public:
Component(string arg):name(arg)
{}
virtual ~Component()
{}
virtual void add(Component&)=0;
virtual void del(Component&)=0;
virtual void display()=0;
protected:
string name;
};
class Composite: public Component
{
public:
Composite(string arg):Component(arg)
{}
void add(Component& arg)
{
lists.push_back(&arg);
}
void del(Component& arg)
{
lists.remove(&arg);
}
void display()
{
cout<<"--"<<name<<endl;
list<Component*>::iterator iter = lists.begin();
while(iter != lists.end())
{
(*iter)->display();
iter++;
}
}
private:
list<Component*> lists;
};
class Leaf: public Component
{
public:
Leaf(string arg):Component(arg)
{}
void add(Component& arg)
{
cout<<"can not call this "<<endl;
}
void del(Component& arg)
{
cout<<"can not call this "<<endl;
}
void display()
{
cout<<"----"<<name<<endl;
}
};
#endif /* COMPOSITE_H_ */
composite.cpp
#include "Composite.h"
void composite()
{
Composite root("root");
Composite level1("level1");
Leaf leaf11("Leaf11");
Leaf leaf12("Leaf12");
Composite level2("level2");
Leaf leaf21("Leaf21");
Leaf leaf22("Leaf22");
Leaf leaf23("Leaf23");
level2.add(leaf21);
level2.add(leaf22);
level2.add(leaf23);
level1.add(leaf11);
level1.add(leaf12);
root.add(level1);
root.add(level2);
root.display();
}
执行结果:
--root
--level1
----Leaf11
----Leaf12
--level2
----Leaf21
----Leaf22
----Leaf23