设计模式-组合模式

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

文章目录


前言

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


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

一、模式定义

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

三、类图

相关推荐
颜酱17 小时前
理解编程范式(前端角度)
设计模式
将编程培养成爱好19 小时前
C++ 设计模式《账本事故:当备份被删光那天》
开发语言·c++·设计模式·备忘录模式
FogLetter21 小时前
设计模式奇幻漂流:从单例孤岛到工厂流水线
前端·设计模式
guangzan1 天前
常用设计模式:代理模式
设计模式
西幻凌云1 天前
认识设计模式——单例模式
c++·单例模式·设计模式·线程安全·饿汉和懒汉
爱吃烤鸡翅的酸菜鱼1 天前
【Java】基于策略模式 + 工厂模式多设计模式下:重构租房系统核心之城市房源列表缓存与高性能筛选
java·redis·后端·缓存·设计模式·重构·策略模式
在未来等你2 天前
AI Agent设计模式 Day 5:Reflexion模式:自我反思与持续改进
设计模式·llm·react·ai agent·plan-and-execute
程序员三藏2 天前
快速弄懂POM设计模式
自动化测试·软件测试·python·selenium·测试工具·设计模式·职场和发展
Lei_3359672 天前
[設計模式]設計模式的作用
设计模式
将编程培养成爱好2 天前
C++ 设计模式《统计辅助功能》
开发语言·c++·设计模式·访问者模式