组合模式 Composite
“数据结构”模式
- 常常有一些组件在内部具有特定的数据结构,如果让客户程序依赖这些特定的数据结构,将极大地破坏组件的复用。这时候,将这些特定数据结构封装在内部,在外部提供统一的接口,来实现与特定数据结构无关的访问,是一种行之有效的解决方案。
- 典型模式
1.Composite
2·Iterator
3·Chain of Resposibility
动机(Motivation)
- 在软件在某些情况下,客户代码过多地依赖于对象容器复杂的内部实现结构,对象容器内部实现结构(而非抽象接口)的变化将引起客户代码的频繁变化,带来了代码的维护性、扩展性等弊端。
- 如何将“客户代码与复杂的对象容器结构”解耦?让对象容器自己来实现自身的复杂结构,从而使得客户代码就像处理简单对象一样来处理复杂的对象容器?
模式定义
将对象组合成树形结构以表示“部分-整体”的层次结构。Composite使得用户对单个对象和组合对象的使用具有一致性(稳定)。—《设计模式》GoF
示例
#include <iostream>
#include <list>
#include <string>
#include <algorithm>
using namespace std;
class Component
{
public:
virtual void process() = 0;
virtual ~Component() {}
};
//树节点
class Composite : public Component {
string name;
list<Component*> elements;
public:
Composite(const string & s) : name(s) {}
void add(Component* element) {
elements.push_back(element);
}
void remove(Component* element) {
elements.remove(element);
}
void process() {
//1. process current node 处理当前节点
cout << "树节点处理: " << name << endl;
//2. process leaf nodes 处理叶子节点
for (auto &e : elements)
e->process(); //多态调用
}
};
//叶子节点
class Leaf : public Component {
string name;
public:
Leaf(string s) : name(s) {}
void process() {
//process current node
cout << "叶子节点处理:" << name << endl;
}
};
void Invoke(Component & c) {
//...
c.process();
//...
}
int main()
{
Composite root("root");
Composite treeNode1("treeNode1");
Composite treeNode2("treeNode2");
Composite treeNode3("treeNode3");
Composite treeNode4("treeNode4");
Leaf leaf1("left1");
Leaf leaf2("left2");
root.add(&treeNode1);
treeNode1.add(&treeNode2);
treeNode2.add(&leaf1);
root.add(&treeNode3);
treeNode3.add(&treeNode4);
treeNode4.add(&leaf2);
/* process(root);
process(leaf2);
process(treeNode3);*/
Invoke(root);
cout << endl;
Invoke(leaf2);
cout << endl;
Invoke(treeNode3);
cout << endl;
getchar();
return 0;
}
输出:
树节点处理: root
树节点处理: treeNode1
树节点处理: treeNode2
叶子节点处理:left1
树节点处理: treeNode3
树节点处理: treeNode4
叶子节点处理:left2
叶子节点处理:left2
树节点处理: treeNode3
树节点处理: treeNode4
叶子节点处理:left2
// 递归处理。既可以是单个的叶子节点,也可以是树节点。(统一的接口)既可以一对一又可以一对多。
// 如何反向追溯?
类图
要点总结
- Composite模式采用树形结构来实现普遍存在的对象容器,从而将“一对多”的关系转化为一对一”的关系,使得客户代码可以一致地(复用)处理对象和对象容器,无需关心处理的是单个的对象,还是组合的对象容器。
- 将“客户代码与复杂的对象容器结构”解耦是Composite的核心思想,解耦之后,客户代码将与纯粹的抽象接口——而非对象容器的内部实现结构——发生依赖,从而更能“应对变化”。
- Composite模式在具体实现中,可以让父对象中的子对象反向追溯;如果父对象有频繁的遍历需求,可使用缓存技巧来改善效率。
参考:GeekBand
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了