19.组合模式(Composite)

意图:将对象组成树状结构以表示"部分-整体"的层次结构,使得Client对单个对象和组合对象的使用具有一致性。
上下文:在树型结构的问题中,Client必须以不同的方式处理单个对象和组合对象。能否提供一种封装,统一简单元素和复杂元素的概念,让对象容器自己来实现自身的复杂结构,让Client可以像处理简单元素一样来处理复杂元素,从而使Client与复杂元素的内部结构解耦?

UML

Component :为Composite中的对象声明接口;在适当情况下,实现所有类公共接口的默认行为;声明一个接口,用于访问和管理Component的子部件;在递归结构中定义一个接口,用于访问一个父部件,并在适当的情况下实现它。
Leaf :在Composite中表示叶子对象。
Composite :存储子部件,并定义有子部件的那些部件的行为。
Client:通过Component接口操作Composite的对象。

代码:

cpp 复制代码
#include <iostream>
#include <list>
using namespace std;
 
class Component
{
public:
    string name;
    Component(string name):name(name){
 
    }
    virtual void add(Component *c) = 0;
    virtual void remove(Component *c) = 0;
    virtual void display(int depth) = 0;
};
 
class Leaf:public Component
{
public:
    // Component interface
    Leaf(string name):Component(name){
 
    }
public:
    void add(Component *c);
    void remove(Component *c);
    void display(int depth);
};
 
void Leaf::add(Component *c )
{
    (void)(c);//消除警告
    cout << "不能向叶子中添加Component" << endl;
}
 
void Leaf::remove(Component *c)
{
    (void)(c);//Warning
    cout << "不能从叶子中删除Component" << endl;
}
 
void Leaf::display(int depth)
{
    cout << string(depth,'-') << this->name << endl;
}
 
class Composite:public Component
{
public:
    list<Component*> children;
    // Component interface
    Composite(string name):Component(name){
 
    }
public:
    void add(Component *c);
    void remove(Component *c);
    void display(int depth);
};
void Composite::add(Component *c)
{
    children.push_back(c);
}
 
void Composite::remove(Component *c)
{
    children.remove(c);
}
 
void Composite::display(int depth)
{
    cout << string(depth,'-') << this->name << endl;
    list<Component*>::iterator it;
    for(it = children.begin();it != children.end();it++){
        Component *c = *it;
        c->display(depth + 2);
    }
}
int main()
{
    Composite *root = new Composite("树干");
    root->add(new Leaf("树叶1"));
    root->add(new Leaf("树叶2"));
 
    Composite *c1 = new Composite("树枝1");
    c1->add(new Leaf("树叶1-1"));
    c1->add(new Leaf("树叶1-2"));
    root->add(c1);
 
    Composite *c1_1 = new Composite("树枝1-1");
    c1_1->add(new Leaf("树叶1-1-1"));
    c1_1->add(new Leaf("树叶1-1-2"));
    c1->add(c1_1);
    root->add(new Leaf("树叶3"));
    root->display(1);
 
    return 0;
}

结果

复制代码
-树干
---树叶1
---树叶2
---树枝1
-----树叶1-1
-----树叶1-2
-----树枝1-1
-------树叶1-1-1
-------树叶1-1-2
---树叶3
相关推荐
odoo中国8 天前
Odoo19制造模块套件功能解析:赋能组合产品生产与库存高效管控
组合模式·制造·odoo19·套件管理·bom套件管理·组合销售
折哥的程序人生 · 物流技术专研8 天前
Java 23 种设计模式:从踩坑到精通 | 组合模式 —— 树形结构处理,部分与整体一视同仁
java·组合模式·java面试·springsecurity·结构型模式·java设计模式·从踩坑到精通
屋外雨大,惊蛰出没17 天前
组合模式(composite)
组合模式
石逸凡1 个月前
论组织本源与钻形式招牌的空子
大数据·组合模式
雪碧聊技术1 个月前
什么是组合模式?一文详解
组合模式
c++之路1 个月前
组合模式(Composite Pattern)
组合模式
likerhood1 个月前
设计模式 · 组合模式(Composite Pattern)
设计模式·组合模式
蜡笔小马1 个月前
07.C++设计模式-组合模式
c++·设计模式·组合模式
多加点辣也没关系1 个月前
设计模式-组合模式
设计模式·组合模式
qq_296553271 个月前
[特殊字符] 数组中的递增三元组:O(n) 时间高效查找,面试必考!
数据结构·算法·面试·职场和发展·组合模式·柔性数组