设计模式-组合模式

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录


前言

软件在某些情况下客户代码过多依赖对象容器复杂的内部实现结构,对象容器内部实现结构的变化将引起客户代码的频繁变化。需要将客户代码和复杂的对象容器结构解耦,让对象容器自己来实现自身复杂的结构。


提示:以下是本篇文章正文内容,下面案例可供参考

一、模式定义

将对象组合成树形结构以表示部分-整体的层次结构。Composite使得用户对单个对象和组合对象的使用具有一致性(稳定)。

二、代码实例

cpp 复制代码
#include <algorithm>

using namespace std;

class Component
{
    public:
    virtual void process() = 0;
    virtual ~Component() {}
};

// 树节点
class Composite: public Component
{
    string name;
    list<Component*> elements;

    public:
        Composite(const string& s): name(s) {}

        void add(Component* c) { elements.push_back(c); }
        void remove(Component* c) { elements.remove(c); }
        void process()
        {
            // process current node

            // process leaf nodes
            for(auto& e: elements)
            {
                e->process();
            }
        }
}

// 叶子节点
class Leaf: public Component
{
    string name;

    public:
        Leaf(const string& s): name(s) {}

        void process() { /* ... */ }
}

// 客户程序
void Invoke(Component* c)
{
    /*前处理*/
    c->process();

    /*后处理*/
}

int main()
{
    Composite root("root");
    Composite treeNode1("treeNode1");
    Composite treeNode2("treeNode2");
    Component treeNode3("treeNode3");
    Component treeNode4("treeNode4");
    Leaf leaf1("leaf1");
    Leaf leaf2("leaf2");

    root.add(&treeNode1);
    treeNode1.add(&treeNode2);
    treeNode2.add(&leaf1);

    root.add(&treeNode3);
    treeNode3.add(&treeNode4);
    treeNode4.add(&leaf2);

    root.process();
}

三、类图

相关推荐
米啦啦.1 小时前
设计模式/
观察者模式·单例模式·设计模式·工厂模式
QuZhengRong2 小时前
【AI】Agent 全栈进阶|Agent 设计模式
人工智能·学习·设计模式·llm·agent
码匠许师傅3 小时前
【设计模式精讲】2. 设计原则基石:SOLID 与几条关键原则
java·设计模式·log4j
AI人工智能+电脑小能手5 小时前
大白话说Java设计模式-41-备忘录模式(源码剖析篇)
java·设计模式·备忘录模式·源码分析·serializable·undo log·spring statemachine
yinchnag6 小时前
CRTP:奇异递归模板模式在 Go 模块系统中的实现
设计模式·go
AI人工智能+电脑小能手7 小时前
大白话说Java设计模式-40-备忘录模式(业务实战篇)
java·设计模式·事务回滚·备忘录模式·状态保存·spring transactional·购物车快照
bryant_meng1 天前
【Codex】Part 19 — Codex Prompt Design Patterns
设计模式·prompt·playbook·结果优先·用证据定义完成
AI人工智能+电脑小能手1 天前
大白话说Java设计模式-38-迭代器模式(业务实战篇)
java·设计模式·迭代器模式·stream·遍历封装·集合通用·分页遍历
qyyyyy5701 天前
芯片 Application Note PDF 怎么读?参考电路、BOM 和调试波形翻译实战
嵌入式硬件·设计模式·机器翻译·web application
程序员贺加贝1 天前
列表导出不够用-SaaS-ERP-单据详情导出的-Provider-模板与文档型-Excel-设计
java·后端·设计模式·架构·excel