设计模式--组合模式(Composite Pattern)

组合模式(Composite Pattern)是一种结构型设计模式,它允许你将对象组合成树形结构,并且能像使用独立对象一样使用它们。

组合模式主要包含以下几个角色:

  1. Component:这是组合中对象声明接口,在适当的情况下,实现所有类共有接口的默认行为。声明一个接口用于访问和管理Component的子部件。
  2. Leaf:在组合中表示叶节点对象,叶节点没有子节点。
  3. Composite:定义有枝节点行为,用来存储子部件,在Component接口中实现与子部件有关操作,如增加(add)和删除(remove)等。

组合模式的主要优点是:

  • 高层模块调用简单:客户端可以一致地使用组合结构和单个对象,简化了客户端与这些对象的交互,让客户端更简单地操作这些对象。
  • 节点自由增加:使用组合模式,我们可以动态地添加、删除和修改对象,也就是说,客户端不必因为业务逻辑的改变而改变。
    组合模式适用于以下场景:
  • 想表示对象的部分-整体层次结构。
  • 希望用户忽略组合对象和单个对象的不同,用户将统一地使用组合结构中的所有对象。

以下是一个简单的C++实现的组合模式(Composite Pattern)示例:

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

// 抽象组件
class Component {
public:
    virtual void operation() = 0;
    virtual void add(Component* c) {}
    virtual void remove(Component* c) {}
    virtual ~Component() {}
};

// 叶子组件
class Leaf : public Component {
public:
    void operation() override {
        std::cout << "Leaf operation..." << std::endl;
    }
};

// 复合组件
class Composite : public Component {
public:
    void operation() override {
        std::cout << "Composite operation..." << std::endl;
        for (Component* c : children) {
            c->operation();
        }
    }

    void add(Component* c) override {
        children.push_back(c);
    }

    void remove(Component* c) override {
        children.erase(std::remove(children.begin(), children.end(), c), children.end());
    }

    ~Composite() {
        for (Component* c : children) {
            delete c;
        }
        children.clear();
    }

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

int main() {
    Composite* composite = new Composite();
    composite->add(new Leaf());
    composite->add(new Leaf());

    Composite* composite2 = new Composite();
    composite2->add(new Leaf());
    composite2->add(new Leaf());

    composite->add(composite2);
    composite->operation();

    delete composite;

    return 0;
}

在这个例子中,Component是抽象组件,定义了operation、add和remove等接口。Leaf是叶子组件,实现了operation接口。Composite是复合组件,除了实现operation接口,还实现了add和remove接口,用于添加和删除子组件。在operation接口中,Composite会调用所有子组件的operation接口。

相关推荐
繁华似锦respect8 分钟前
C++ 设计模式之代理模式详细介绍
linux·开发语言·c++·windows·设计模式·代理模式·visual studio
__万波__13 小时前
二十三种设计模式(二)--工厂方法模式
java·设计模式·工厂方法模式
前端老宋Running14 小时前
React 的“时光胶囊”:useRef 才是那个打破“闭包陷阱”的救世主
前端·react.js·设计模式
Tzarevich15 小时前
从字面量到原型链:JavaScript 面向对象的完整进化史
javascript·设计模式
繁华似锦respect19 小时前
C++ 设计模式之工厂模式详细介绍
java·linux·c++·网络协议·设计模式
想要成为祖国的花朵19 小时前
基于多设计模式的抽奖系统__测试报告
java·selenium·测试工具·jmeter·设计模式·测试用例·安全性测试
重铸码农荣光1 天前
JavaScript 面向对象编程:从字面量到原型继承的深度探索
前端·javascript·设计模式
L***d6701 天前
Spring Boot 经典九设计模式全览
java·spring boot·设计模式
未可知7771 天前
软件设计师(下午题2)、UML与设计模式
算法·设计模式·职场和发展·uml
繁华似锦respect1 天前
C++ 设计模式之单例模式详细介绍
服务器·开发语言·c++·windows·visualstudio·单例模式·设计模式