设计模式-组合模式

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


前言

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


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

一、模式定义

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

二、代码实例

#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. 设计模式——组合模式

    2023-12-25 14:10:04       26 阅读
  2. 设计模式组合模式

    2023-12-25 14:10:04       12 阅读
  3. 设计模式组合模式

    2023-12-25 14:10:04       11 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-25 14:10:04       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-25 14:10:04       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-25 14:10:04       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-25 14:10:04       18 阅读

热门阅读

  1. 国产化之路 Linux Mono下的asp.net 开发笔记(一)

    2023-12-25 14:10:04       36 阅读
  2. void类型指针和函数指针

    2023-12-25 14:10:04       30 阅读
  3. 盘点 | 2023年针对国内的电子邮件安全事件

    2023-12-25 14:10:04       33 阅读
  4. obs video-io.c

    2023-12-25 14:10:04       29 阅读
  5. 策略模式(Strategy)

    2023-12-25 14:10:04       36 阅读
  6. Transformer 模型设计的灵感

    2023-12-25 14:10:04       33 阅读
  7. 【题解】洛谷 P9183 [USACO23OPEN] FEB B

    2023-12-25 14:10:04       38 阅读
  8. git拉取远程分支到本地

    2023-12-25 14:10:04       36 阅读
  9. 【前端基础】uniapp、axios 获取二进制图片

    2023-12-25 14:10:04       43 阅读
  10. 使用Uniapp随手记录知识点

    2023-12-25 14:10:04       37 阅读
  11. DrmOpenWithType

    2023-12-25 14:10:04       32 阅读