9 结构型模式-----组合模式

本文深入探讨了组合模式,一种将对象组合成树形结构的设计模式,用于表示“整体-部分”的层次关系,使对部分和整体的操作保持一致性。通过具体代码示例,展示了组合模式的实现方法,包括抽象部件类、组合容器类和叶子结点类的设计。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

模式动机(Composite Pattern)将对象组合成树形结构来表示“整体-部分”层次。操作时,使得对部分的操作与对整体的操作具有一致性。

模式结构图:

 

 

典型的Composite结构为:

 

模式代码:

bt_组合模式.h

#ifndef CP_H
#define CP_H
#include <iostream>
#include <vector>
using namespace std;

/*
    抽象部件类
*/
class Composite;
class Component
{
public:
    virtual ~Component(){ }
    virtual void Add(Component* pc) = 0;
    virtual void Remove(Component* pc) = 0;
    virtual Component* GetChild(unsigned int i) = 0;
    virtual void Operation() = 0;               // 一致的操作接口

};

/*
    组合容器类,其中既可以放组合器,又可以放叶子结点
*/
class Composite : public Component
{
public:
    virtual void Add(Component* pc)
    {
        this->children.push_back(pc);
    }
    virtual void Remove(Component* pc)
    {
        cout << "删除部件" << endl;
    }
    virtual Component* GetChild(unsigned int i)
    {
        if(i < this->children.size())
            return this->children[i];
        else
            return NULL;
    }
    virtual void Operation()
    {
        cout << "执行容器的相应操作" << endl;
        vector<Component*>::iterator iter = this->children.begin();
        for(; iter != this->children.end(); iter++)
            (*iter)->Operation();
    }

private:
    vector<Component*> children;
};

/*
    叶子结点类
*/
class Leaf : public Component
{
public:
    virtual void Add(Component* pc)
    {
        cerr << "操作错误" << endl;
        return ;
    }
    virtual void Remove(Component* pc)
    {
        cerr << "操作错误" << endl;
        return ;
    }
    virtual Component* GetChild(unsigned int i)
    {
        cout << "操作错误" << endl;
        return NULL;
    }
    virtual void Operation()
    {
        cout << "执行叶子的相应操作" << endl;
    }
};

#endif // CP_H
#include "bt_组合模式.h"

int main()
{
    cout << "***** 组合模式测试 *****" << endl;
    Component* pC = new Composite;
    Composite* pS = new Composite;
    Leaf* pL1 = new Leaf;
    Leaf* pL2 = new Leaf;

    pC->Add(pL1);
    pS->Add(pL2);
    pC->Add(pS);
    pC->Operation();

    cout << endl;
    pL1->Add(pL2);

    delete pL2;
    delete pL1;
    delete pS;
    delete pC;

    return 0;
}

模式优缺点:

客户端可以使用一致的方法操作对象,无论该对象是Leaf还是Composite。缺点是设计更加复杂了,而且一般只适用于树状分层的关系。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值