设计模式-组合模式

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

文章目录


前言

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


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

一、模式定义

将对象组合成树形结构以表示部分-整体的层次结构。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 小时前
java23种设计模式-模板方法模式
java·设计模式·模板方法模式
攻城狮7号2 小时前
【第八节】C++设计模式(结构型模式)-Decorator(装饰器)模式
c++·设计模式·装饰器模式
北城望戈4 小时前
工作中遇到的设计模式整理
java·设计模式
LuckyLay4 小时前
Golang学习笔记_40——模版方法模式
笔记·学习·设计模式·golang·模板方法模式
Forget the Dream7 小时前
设计模式之责任链模式
java·c++·设计模式·责任链模式
Duramentee7 小时前
C++ 设计模式 十二:责任链模式 (读书 现代c++设计模式)
c++·设计模式·责任链模式
_真相只有一个7 小时前
行为型模式 - 职责链模式 (Chain of Responsibility Pattern)
设计模式·责任链模式
Forget the Dream7 小时前
设计模式之代理模式
java·c++·设计模式·代理模式
帅的飞起来7 小时前
设计模式--spring中用到的设计模式
java·spring·设计模式
攻城狮7号10 小时前
【第十节】C++设计模式(结构型模式)-Flyweight( 享元)模式
c++·设计模式·享元模式