组合模式通过统一接口处理树形结构中的个体与容器,结合递归实现自然遍历。核心为抽象组件类定义操作与子节点管理,叶子节点仅实现操作,容器节点维护子组件并递归调用其方法。示例中根节点调用operation后逐层展开,体现深度优先遍历。还可扩展查找、统计等递归功能,如findByName递归搜索目标节点。优势在于接口统一、可扩展性强、逻辑清晰,配合智能指针保障内存安全,适用于文件系统、UI树等场景。

在C++中,组合模式(Composite Pattern)常用于处理树形结构,将单个对象与对象组合以统一方式对待。当它与递归操作结合时,能够自然地遍历和操作整个层级结构,特别适合如文件系统、UI控件树、组织结构等场景。
组合模式的核心是定义一个抽象组件类,包含个体(Leaf)和容器(Composite)的共同接口。容器可以包含多个子组件,并提供添加、删除和访问子节点的方法。
以下是一个简化实现:
#include <iostream>
#include <vector>
#include <memory>
<p>// 抽象组件类
class Component {
public:
virtual ~Component() = default;
virtual void operation() const = 0;
virtual void add(std::shared_ptr<Component> child) {
throw std::runtime_error("Not supported.");
}
virtual void remove(const Component* child) {
throw std::runtime_error("Not supported.");
}
virtual const std::vector<std::shared_ptr<Component>>& getChildren() const {
static std::vector<std::shared_ptr<Component>> empty;
return empty;
}
};</p><p>// 叶子节点
class Leaf : public Component {
std::string name;
public:
explicit Leaf(const std::string& n) : name(n) {}
void operation() const override {
std::cout << "Leaf " << name << " operation.\n";
}
};</p><p>// 容器节点
class Composite : public Component {
std::string name;
std::vector<std::shared_ptr<Component>> children;
public:
explicit Composite(const std::string& n) : name(n) {}</p><pre class='brush:php;toolbar:false;'>void operation() const override {
std::cout << "Composite " << name << " operation:\n";
for (const auto& child : children) {
child->operation(); // 递归调用
}
}
void add(std::shared_ptr<Component> child) override {
children.push_back(child);
}
void remove(const Component* target) override {
children.erase(
std::remove_if(children.begin(), children.end(),
[target](const std::shared_ptr<Component>& ptr) {
return ptr.get() == target;
}),
children.end());
}
const std::vector<std::shared_ptr<Component>>& getChildren() const override {
return children;
}};
立即学习“C++免费学习笔记(深入)”;
组合模式中,operation() 方法在容器中自动递归调用其子节点的 operation(),形成深度优先遍历。这种设计使得客户端无需关心当前对象是叶子还是复合体,统一调用即可触发整棵树的操作。
示例使用:
int main() {
auto root = std::make_shared<Composite>("Root");
auto branch1 = std::make_shared<Composite>("Branch1");
auto branch2 = std::make_shared<Composite>("Branch2");
<pre class='brush:php;toolbar:false;'>auto leaf1 = std::make_shared<Leaf>("Leaf1");
auto leaf2 = std::make_shared<Leaf>("Leaf2");
auto leaf3 = std::make_shared<Leaf>("Leaf3");
branch1->add(leaf1);
branch1->add(leaf2);
branch2->add(leaf3);
root->add(branch1);
root->add(branch2);
root->operation(); // 递归执行整个结构
return 0;}
输出结果会逐层展开每个节点的操作,体现递归遍历过程。
除了 operation(),还可以添加如查找、统计、序列化等递归方法。例如实现一个搜索功能:
bool findByName(const Component* comp, const std::string& target) {
if (auto leaf = dynamic_cast<const Leaf*>(comp)) {
return leaf->getName() == target; // 需为Leaf添加getName()
}
if (auto composite = dynamic_cast<const Composite*>(comp)) {
for (const auto& child : composite->getChildren()) {
if (findByName(child.get(), target)) {
return true;
}
}
}
return false;
}
这个函数利用递归深入每一层,直到找到匹配的叶子节点。
基本上就这些。组合模式搭配递归,让C++中处理层次化数据变得直观高效,不复杂但容易忽略细节,比如异常安全和内存管理,建议使用智能指针避免泄漏。
以上就是C++组合模式与递归操作结合实现的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号