模式定义:将对象组合成树形结构以表示“部分-整体”的层次结构。Compostie使得用户对单个对象和组合对象的使用具有一致性。
代码实现如下:
#include<list>
#include<iostream>
#include<string>
class Component {
public:
Component(std::string name): node(name) {
}
virtual void process()=0;
virtual ~Component(){}
std::string node;
};
class Composite: public Component {
public:
Composite(std::string name): Component(name){}
virtual void process() {
std::cout << node << std::endl;
for (auto& it: tree){
it->process();
}
}
void add(Component* com) {
tree.push_back(com);
}
void remove(Component* com) {
tree.remove(com);
}
private:
std::list<Component*> tree;
};
class Leaf: public Component {
public :
Leaf(std::string name):Component(name){}
virtual void process(){
std::cout << node << std::endl;
}
};
int main(int argc, char** argv) {
Composite root("root");
Composite node1("node1");
Composite node2("node2");
Leaf leaf1("leaf1");
Leaf leaf2("leaf2");
Leaf leaf3("leaf3");
root.add(&node1);
root.add(&node2);
node1.add(&leaf1);
node1.add(&leaf2);
node2.add(&leaf3);
root.process();
return 0;
}