设计模式--组合模式

引言

在面向对象设计的世界里,组合模式(Composite Pattern) 是一种结构型设计模式,旨在让客户端以一致的方式处理个体对象和组合对象,从而简化复杂的层次结构管理。该模式通过定义包含组件和容器组件的类层次结构,使得用户可以忽略单个对象和组合对象的区别,统一进行操作。

应用场景
  • 当你需要表示对象的部分-整体层次结构时,比如文件系统中的目录与文件、组织结构中的部门与员工。
  • 需要对对象进行递归操作,如遍历、搜索、计数等,且这些操作既适用于单个对象也适用于组合对象。
  • 希望用户能够以统一的方式处理单个对象和组合对象,而无需关心它们的具体类型。
使用技巧与注意事项
  • 明确"叶子"与"枝干":在组合模式中,"叶子"是不可再分解的基本对象,而"枝干"是可以包含其他"枝干"或"叶子"的复合对象。
  • 实现统一接口:确保所有组件(无论是叶子还是枝干)都实现了相同的接口,以便客户端能以相同的方式处理它们。
  • 适当使用递归:利用递归可以简化对组合结构的操作,但也要注意避免过深的递归导致栈溢出。
  • 考虑边界情况:正确处理空集合和单个对象的情况,避免不必要的复杂性。
C++代码示例

假设我们要构建一个简单的菜单系统,其中菜单项可以是单一的菜品(叶子节点),也可以是包含多个子菜单项的组合菜单(枝干节点)。这个场景完美匹配组合模式的应用。

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

// 抽象组件:菜单项接口
class MenuComponent {
public:
    virtual ~MenuComponent() {}
    virtual void printName() const = 0;
    virtual void add(MenuComponent* menuComponent) = 0;
    virtual void remove(MenuComponent* menuComponent) = 0;
    virtual MenuComponent* getChild(int i) const = 0;
};

// 叶子组件:具体菜品
class MenuItem : public MenuComponent {
public:
    MenuItem(const std::string& name) : name_(name) {}
    void printName() const override { std::cout << name_ << std::endl; }
    void add(MenuComponent* menuComponent) override { /* 不支持 */ }
    void remove(MenuComponent* menuComponent) override { /* 不支持 */ }
    MenuComponent* getChild(int i) const override { return nullptr; }

private:
    std::string name_;
};

// 枝干组件:组合菜单
class Menu : public MenuComponent {
public:
    Menu(const std::string& name) : name_(name) {}
    void printName() const override { std::cout << name_ << std::endl; }
    void add(MenuComponent* menuComponent) override { components.push_back(menuComponent); }
    void remove(MenuComponent* menuComponent) override {
        for (auto it = components.begin(); it != components.end(); ++it) {
            if (*it == menuComponent) {
                components.erase(it);
                break;
            }
        }
    }
    MenuComponent* getChild(int i) const override {
        if (i >= 0 && i < components.size()) {
            return components[i];
        }
        return nullptr;
    }

    void printMenu() const {
        printName();
        for (const auto& component : components) {
            component->printName();
        }
    }

private:
    std::string name_;
    std::vector<MenuComponent*> components;
};

int main() {
    MenuComponent* pancakeHouseMenu = new Menu("Pancake House Menu");
    MenuComponent* dinerMenu = new Menu("Diner Menu");
    MenuComponent* cafeMenu = new Menu("Cafe Menu");

    MenuItem* item1 = new MenuItem("Pancakes");
    MenuItem* item2 = new MenuItem("Waffles");
    MenuItem* item3 = new MenuItem("Coffee");

    ((Menu*)pancakeHouseMenu)->add(item1);
    ((Menu*)pancakeHouseMenu)->add(item2);

    ((Menu*)dinerMenu)->add(item3);

    MenuComponent* allMenus = new Menu("All Menus");
    allMenus->add(pancakeHouseMenu);
    allMenus->add(dinerMenu);
    allMenus->add(cafeMenu);

    ((Menu*)allMenus)->printMenu();

    delete allMenus; // 注意释放内存

    return 0;
}

在这个例子中,MenuComponent是抽象基类,定义了所有菜单项共有的接口。MenuItem作为叶子节点,实现了单个菜品的功能;Menu作为枝干节点,不仅实现了菜单项的功能,还能包含其他MenuComponent对象,形成树状结构。通过组合模式,我们可以轻松地管理和遍历整个菜单系统,而无需区分处理的是单一菜品还是包含子菜单的组合菜单。

相关推荐
Zane19943 天前
一个 new 就能创建对象,为什么还要拆出单例、工厂、建造者、原型四种模式?
设计模式
怕浪猫4 天前
一行命令复刻爆款视频,我把 Hypit 从安装跑到了出片
人工智能·设计模式·程序员
Zane19944 天前
函数式编程里的函数,其实不是你天天写的那个函数——三大编程范式的边界在哪
设计模式
Zane19945 天前
策略模式现在该不该上?一次讲清楚过度设计和设计不足怎么找平衡
设计模式
她说..5 天前
常见设计模式-模板方法模式
java·spring·设计模式·springboot
xiaofeiyang1505 天前
第六章 · 桥接 — 三支毛笔,画出九种颜色
设计模式
Shadow(⊙o⊙)6 天前
OTOL设计模式 One Thread One Loop
服务器·网络·设计模式
sarasuki7 天前
如何让LLM 能在半夜偷偷打开网易云呢?
人工智能·设计模式·agent
小王师傅667 天前
【设计模式】装饰模式(四):框架源码实战——从 Java I/O 到 Spring 到 MyBatis
java·设计模式
执明wa7 天前
Android RecyclerView 多类型, 多种 Item
android·xml·开发语言·设计模式·android studio