组合设计模式通过统一接口让客户端一致处理单个与组合对象,适用于树形结构;定义抽象基类Component声明操作接口,叶子节点Leaf仅实现operation(),复合节点Composite重写add/remove/getChild以管理子节点并转发请求,从而实现透明的层次结构操作。

在C++中实现组合设计模式(Composite Pattern),核心目标是让客户端可以统一处理单个对象和组合对象,特别适用于树形结构的场景,比如文件系统、UI控件树、组织架构等。通过定义一致的接口,叶子节点和容器节点对外表现一致。
所有节点,无论是叶子还是容器,都继承自同一个基类。这个基类声明操作接口,如添加、删除、获取子节点以及执行某种行为。
示例代码:
class Component {
public:
virtual ~Component() = default;
virtual void operation() const = 0;
virtual void add(Component* component) {
throw std::runtime_error("Not supported.");
}
virtual void remove(Component* component) {
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;"><pre class="brush:php;toolbar:false;">void add(Component* component) override {
children.push_back(component);
}
void remove(Component* component) override {
children.erase(
std::remove(children.begin(), children.end(), component),
children.end()
);
}
Component* getChild(int index) override {
if (index < 0 || index >= children.size()) return nullptr;
return children[index];
}};
客户端无需区分是叶子还是容器,直接调用基类接口即可完成操作。
示例用法:
int main() {
Composite root;
Leaf leaf1, leaf2;
Composite subNode;
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">subNode.add(&leaf1);
root.add(&subNode);
root.add(&leaf2);
root.operation(); // 统一调用,自动遍历
return 0;}
输出结果:
Composite operation: Composite operation: Leaf operation. Leaf operation.
组合模式成功的关键在于:
基本上就这些。只要接口设计清晰,C++中的组合模式能很好地解耦树形结构的操作逻辑。
以上就是c++++如何实现组合设计模式(Composite)_c++处理树形结构的统一接口的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号