C++设计模式——组合模式(Composite)
2023-09-14 09:07:08 时间
组合模式
在软件某些情况下,客户代码过多地依赖于对象容器复杂的内部实现结构,对象容器内部实现结构(而非抽象接口)的变化将引起客户代码的频繁变化,带来了代码的维护性、扩展性弊端。
组合模式:将对象组合成树形结构以表示“部分-整体”的层次结构。Composite使得用户对单个对象和组合对象的使用具有一致性(稳定)
#include<iostream>
#include<list>
#include<string>
#include<algorithm>
using namespace std;
class Component {
public:
virtual void process() = 0;
virtual ~Component() {}
};
//树的节点
class Composite :public Component {
private:
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() {
//先处理当前节点,然后处理叶子结点
for (auto& e : elements) {
e->process();//多态调用
}
}
};
class Leaf :public Component {
private:
string name;
public:
Leaf(const string& s):name(s){}
void process() {
//处理当前节点
cout << "process current node... " << name << endl;
}
};
int main()
{
Composite root("root");
Composite treeNode1("treeNode1");
Composite treeNode2("treeNode2");
Composite treeNode3("treeNode3");
Composite treeNode4("treeNode4");
Leaf leaf1("leaf1");
Leaf leaf2("leaf2");
root.add(&treeNode1);
treeNode1.add(&treeNode2);
treeNode2.add(&leaf1);
root.add(&treeNode3);
treeNode3.add(&treeNode4);
treeNode4.add(&leaf2);
root.process();
treeNode2.process();
return 0;
}
结果如下:
要点:
使用树形结构实现“一对多”关系转化为“一对一”关系。将客户代码与复杂的内部容器结构解耦。具体实现中,可以让父对象中的子对象反向回溯,若父对象有频繁的遍历需求,可使用缓存技术改善效率。
相关文章
- EasyC++48,内部链接性和无链接性
- c++语言截取字符串,详解C++ string常用截取字符串方法
- 判断DLL文件是C/C++动态链接库还是.NET程序集及查看DLL依赖
- C++输出对象在内存中的地址
- C++stl库_c++库
- C++ Primer Plus习题及答案-第十三章
- c 线程安全的单例模式-设计模式之单例模式(C++版)
- c 线程安全的单例模式-std string与线程安全_这才是现代C++单例模式简单又安全的实现
- C++ 实现多线程生产者消费者模式
- C++STL——stack与queue
- C++设计模式--Visitor模式
- C++语言的历史
- C++ piecewise_linear_distribution分段线性分布随机数用法详解
- 线性搜索算法(C++)详解
- C++ seekp和seekg函数用法详解
- C++中的单例模式介绍
- c/c++语言位域注意事项分析
- C++运算符重载的方法详细解析
- C++结构体数组详细解析
- 通过c++11改进我们的模式之改进命令模式
- C++中重载、重写(覆盖)和隐藏的区别实例分析