大话设计模式之组合模式

组合模式是一种结构型设计模式,它允许你将对象组合成树形结构以表现"整体-部分"的层次结构。组合模式使得用户对单个对象和组合对象的处理具有一致性。

在组合模式中,有两种类型的对象:

  1. 叶节点(Leaf): 叶节点是树结构中的最终节点,它没有子节点。它通常执行最终操作。

  2. 组合节点(Composite): 组合节点是包含子节点的节点,它可以包含叶节点或其他组合节点。组合节点通常将请求委派给其子节点,并对结果进行汇总。

cpp 复制代码
#include <iostream>
#include <vector>

// 抽象组件类
class Component {
public:
    virtual ~Component() {}
    virtual void operation() const = 0;
};

// 叶节点类
class Leaf : public Component {
public:
    void operation() const override {
        std::cout << "Leaf operation" << std::endl;
    }
};

// 组合节点类
class Composite : public Component {
public:
    void add(Component* component) {
        children_.push_back(component);
    }

    void remove(Component* component) {
        // 移除 component
        children_.erase(std::remove(children_.begin(), children_.end(), component), children_.end());
    }

    void operation() const override {
        std::cout << "Composite operation" << std::endl;
        // 调用所有子节点的操作
        for (const auto& child : children_) {
            child->operation();
        }
    }

private:
    std::vector<Component*> children_;
};

int main() {
    Leaf leaf1, leaf2;
    Composite composite1, composite2;

    composite1.add(&leaf1);
    composite1.add(&leaf2);

    composite2.add(&composite1);

    leaf1.operation();
    std::cout << std::endl;

    composite1.operation();
    std::cout << std::endl;

    composite2.operation();

    return 0;
}

/*
在这个示例中,Component 是抽象组件类,它声明了所有组件的通用操作。Leaf 类是叶节点,
它实现了具体的操作。Composite 类是组合节点,它可以包含叶节点或其他组合节点,
并实现了操作以处理其子节点。

在 main() 函数中,我们创建了几个叶节点和组合节点,并将它们组合成树形结构。
然后我们分别调用了叶节点和组合节点的操作,验证了组合模式的正确性。
*/
相关推荐
Dabei2 小时前
Android 无障碍服务实现美团/微信自动化:客户端开发实践
前端·设计模式
巴沟旮旯儿5 小时前
vite项目配置文件和打包
前端·设计模式
雪度娃娃6 小时前
设计模式——单例模式
开发语言·c++·设计模式
逝水如流年轻往返染尘8 小时前
设计模式之单例模式
单例模式·设计模式
雪度娃娃1 天前
设计模式-UML
设计模式
kyriewen111 天前
代码写成一锅粥?3个设计模式让你的项目“起死回生”
开发语言·前端·javascript·设计模式·ecmascript
geovindu2 天前
go: Mediator Pattern
设计模式·golang·中介者模式
kyriewen2 天前
代码写成一锅粥?3个设计模式让你的项目“起死回生”
前端·javascript·设计模式
Pkmer2 天前
古法编程: 适配器模式
java·设计模式