一、UML图
二、包含的角色
Component接口,描述了树中简单项目和复杂项目所共有的操作。
Leaf类, 是树的基本结构, 它不包含子项目。一般情况下, 叶节点最终会完成大部分的实际工作, 因为它们无法将工作指派给其他部分。
Composite类,是包含叶节点或其他容器等子项目的单位。 容器不知道其子项目所属的具体类, 它只通过通用的组件接口与其子项目交互。容器接收到请求后会将工作分配给自己的子项目, 处理中间结果, 然后将最终结果返回给客户端。
三、特点
组合模式为你提供了两种共享公共接口的基本元素类型: 简单叶节点和复杂容器。 容器中可以包含叶节点和其他容器。 这使得你可以构建树状嵌套递归对象结构
组合模式中定义的所有元素共用同一个接口。 在这一接口的帮助下, 客户端不必在意其所使用的对象的具体类。
四、代码实现
Component接口
#pragma once
#include <string>
using namespace std;
class Component
{
public:
Component(const std::string &key): _key(key){}
virtual ~Component() {}
protected:
string _key;
public:
virtual void Excute() = 0;
};
Leaf类
#pragma once
#include "Component.h"
#include <iostream>
class Leaf : public Component
{
public:
Leaf(const std::string &key):Component(key){}
~Leaf(){
std::cout <<_key <<" Leaf析构" << std::endl;
}
virtual void Excute() override
{
std::cout << "Leaf"<< _key <<"excute" << std::endl;
}
};
Composite类
#pragma once
#include "Component.h"
#include <iostream>
#include <string>
#include <list>
class Composite : public Component
{
public:
Composite(const std::string &key):Component(key){}
~Composite()
{
std::cout <<_key << " Composite析构" << std::endl;
for (auto it : _componentList)
{
delete it;
}
_componentList.clear();
}
private:
std::list<Component *> _componentList;
public:
virtual void Excute() override
{
for (auto it : _componentList)
{
it->Excute();
}
}
virtual void Remove(Component *component)
{
_componentList.remove(component);
}
virtual void Add(Component *component)
{
_componentList.push_back(component);
}
};
main
#include "Composite.h"
#include "Leaf.h"
int main()
{
Composite *root = new Composite("root");
Composite *bin = new Composite("bin");
Composite *tmp = new Composite("tmp");
Leaf *leaf1 = new Leaf("leaf1.txt");
Leaf *leaf2 = new Leaf("leaf2.txt");
root->Add(bin);
root->Add(tmp);
bin->Add(leaf1);
tmp->Add(leaf2);
root->Excute();
delete root;
return 0;
}