组合设计模式通过统一接口处理单个与组合对象,C++中定义Component基类声明操作与子节点管理方法,Leaf实现自身行为,Composite维护子节点列表并转发请求,实现树形结构透明访问。

组合设计模式(Composite Pattern)是一种结构型设计模式,它允许你将对象组合成树形结构来表示“整体-部分”层次关系。C++中实现该模式的关键是定义一个统一的接口,让客户端可以透明地处理单个对象和组合对象,特别适合处理具有层级结构的数据,比如文件系统、UI控件树或组织架构。
首先定义一个抽象基类(Component),声明所有具体对象共有的操作,包括业务方法和用于管理子节点的方法。
class Component {
public:
virtual ~Component() = default;
virtual void operation() const = 0;
virtual void add(Component* child) {
throw std::runtime_error("Not supported.");
}
virtual void remove(Component* child) {
throw std::runtime_error("Not supported.");
}
virtual Component* getChild(int index) {
throw std::runtime_error("Not supported.");
}
};
这个接口为叶节点和容器节点提供统一访问方式。叶节点不需要添加/删除功能,调用时抛出异常即可,也可根据需求在编译期禁用。
叶子对象不包含子节点,只实现自身行为;容器对象维护子节点列表,并将请求转发给它们。
立即学习“C++免费学习笔记(深入)”;
class Leaf : public Component {
public:
void operation() const override {
std::cout << "Leaf operation.\n";
}
};
<p>class Composite : public Component {
private:
std::vector<Component*> children;</p><p>public:
void operation() const override {
std::cout << "Composite operation:\n";
for (const auto& child : children) {
child->operation();
}
}</p><pre class='brush:php;toolbar:false;'>void add(Component* child) override {
children.push_back(child);
}
void remove(Component* child) override {
children.erase(
std::remove(children.begin(), children.end(), child),
children.end()
);
}
Component* getChild(int index) override {
return index < children.size() ? children[index] : nullptr;
}};
客户端代码无需区分叶子和组合对象,统一通过基类指针操作。
int main() {
Composite root;
Composite branch;
Leaf leaf1, leaf2, leaf3;
<pre class='brush:php;toolbar:false;'>branch.add(&leaf1);
branch.add(&leaf2);
root.add(&branch);
root.add(&leaf3);
root.operation(); // 触发整个树的操作
return 0;}
输出结果会先打印“Composite operation”,然后依次执行 branch 和 leaf3 的操作,branch 再递归调用其子节点。这种递归调用正是组合模式的核心优势。
上面例子使用裸指针,实际项目建议改用 std::unique_ptr 避免内存泄漏。
class Composite : public Component {
private:
std::vector<std::unique_ptr<Component>> children;
<p>public:
void add(std::unique_ptr<Component> child) {
children.push_back(std::move(child));
}</p><pre class='brush:php;toolbar:false;'>void operation() const override {
std::cout << "Composite operation:\n";
for (const auto& child : children) {
child->operation();
}
}
// remove 和 getChild 可根据需要调整返回引用或指针};
客户端创建对象时使用 make_unique,由容器自动管理生命周期。
基本上就这些。组合模式通过统一接口简化了树形结构的操作,尤其适用于需要递归处理嵌套对象的场景。只要明确区分叶节点与组合节点职责,就能写出清晰可扩展的代码。
以上就是C++怎么实现一个组合设计模式_C++结构型模式与树形结构表示的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号