组合模式
- 将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性
- 需求中是体现部分与整体层次的结构时,希望用户可以忽略组合对象与单个对象的不同,统一地使用组合结构中的所有对象时,考虑使用组合模式
- 整体和部分可以被一致对待
#include <iostream>
#include <string>
#include <list>
#include <memory>
using namespace std;
//接口
class Componet;
typedef shared_ptr<Componet> COMPONET;
class Componet
{
public:
Componet(string &_name):name(_name) {}
virtual ~Componet() = 0 {}
virtual void Add(COMPONET c) = 0;
virtual void Remove(COMPONET c) = 0;
virtual void Display(int depth)
{
for (int i = 0; i < depth; i++)
cout << "-";
cout << name << endl;
}
protected:
string name;
};
//叶子
class Leaf : public Componet
{
public:
Leaf(string &_name): Componet(_name) {}
~Leaf() {}
// 通过 Componet 继承
virtual void Remove(COMPONET c) override
{
cout << "Cannot remove from a leaf" << endl;
}
virtual void Display(int depth) override
{
Componet::Display(depth);
}
virtual void Add(COMPONET c)
{
cout << "Cannot add to a leaf" << endl;
}
};
//分支
class Composite : public Componet
{
public:
Composite(string &_name) : Componet(_name) {}
~Composite() {}
// 通过 Componet 继承
virtual void Remove(COMPONET c) override
{
children.remove(c);
}
virtual void Display(int depth) override
{
Componet::Display(depth);
for (auto itr : children)
{
itr->Display(depth + 3);
}
}
virtual void Add(COMPONET c)
{
children.push_back(c);
}
private:
list<COMPONET> children;
};
int main()
{
//建立根
COMPONET root(new Composite(string("root")));
//添加两片叶子到根
root->Add(COMPONET(new Leaf(string("Leaf A"))));
root->Add(COMPONET(new Leaf(string("Leaf B"))));
//创建分支
COMPONET compositeX(new Composite(string("composite X")));
compositeX->Add(COMPONET(new Leaf(string("Leaf XA"))));
compositeX->Add(COMPONET(new Leaf(string("Leaf XB"))));
//分支挂在根上
root->Add(compositeX);
//创建分支
COMPONET compositeY(new Composite(string("composite Y")));
compositeY->Add(COMPONET(new Leaf(string("Leaf YA"))));
compositeY->Add(COMPONET(new Leaf(string("Leaf YB"))));
//分支挂在另一个分支上
compositeX->Add(compositeY);
//添加一片叶子
root->Add(COMPONET(new Leaf(string("Leaf C"))));
COMPONET leaf(new Leaf(string("Leaf D")));
root->Add(leaf);//添加叶子
root->Remove(leaf);//移除叶子
//显示树形结构
root->Display(1);
getchar();
return 0;
}
![](https://img-blog.csdnimg.cn/20190711172450465.png)