设计模式--组合模式(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接口。

相关推荐
Mr_WangAndy15 小时前
C++设计模式_行为型模式_策略模式Strategy
c++·设计模式·策略模式·依赖倒置原则
LoveXming15 小时前
Chapter11—适配器模式
c++·设计模式·适配器模式·开闭原则
杯莫停丶16 小时前
设计模式之:单例模式
java·单例模式·设计模式
WaWaJie_Ngen18 小时前
【设计模式】工厂模式(Factory)
c++·设计模式·简单工厂模式·工厂方法模式·抽象工厂模式
YuanlongWang18 小时前
C# 设计模式——工厂模式
开发语言·设计模式·c#
消失的旧时光-194319 小时前
MQTT主题架构的艺术:从字符串拼接走向设计模式
设计模式
Code_Geo1 天前
agent设计模式:第三章节—并行化
java·设计模式·agent·并行化
Asort1 天前
JavaScript设计模式(十七)——中介者模式 (Mediator):解耦复杂交互的艺术与实践
前端·javascript·设计模式
czy87874751 天前
软件设计模式
设计模式
Hero | 柒1 天前
设计模式之单例模式
java·单例模式·设计模式