设计模式-组合模式

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

文章目录


前言

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


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

一、模式定义

将对象组合成树形结构以表示部分-整体的层次结构。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();
}

三、类图

相关推荐
仅此,2 小时前
Java请求进入Python FastAPI 后,请求体为空,参数不合法
java·spring boot·python·组合模式·fastapi
大厂技术总监下海6 小时前
为何顶尖科技公司都依赖它?解码 Protocol Buffers 背后的高性能、可演进设计模式
分布式·设计模式
EnzoRay6 小时前
代理模式
设计模式
weixin_478433327 小时前
iluwatar 设计模式
java·开发语言·设计模式
郝学胜-神的一滴9 小时前
Python面向对象编程:解耦、多态与魔法艺术
java·开发语言·c++·python·设计模式·软件工程
__万波__9 小时前
二十三种设计模式(十六)--迭代器模式
java·设计模式·迭代器模式
范纹杉想快点毕业21 小时前
返璞归真还是拥抱现代?——嵌入式研发中的“裸机开发”与RTOS全景解析
c语言·数据库·mongodb·设计模式·nosql
代码笔耕1 天前
面向对象开发实践之消息中心设计(四)--- 面向变化的定力
java·设计模式·架构
程序员泠零澪回家种桔子1 天前
ReAct Agent 后端架构解析
后端·spring·设计模式·架构
阿闽ooo1 天前
深入浅出享元模式:从图形编辑器看对象复用的艺术
c++·设计模式·编辑器·享元模式