08 组合模式

组合模式(Composite Pattern),又叫部分整体模式,是用于把一组相似的对象当作一个单一的对象。组合模式依据树形结构来组合对象,用来表示部分以及整体层次。这种类型的设计模式属于结构型模式,它创建了对象组的树形结构。使得客户以一致的方式处理单个对象以及对象的组合。

组合模式实现的最关键的地方是:简单对象和复合对象必须实现相同的接口。这就是组合模式能够将组合对象和简单对象进行一致处理的原因。

组合模式的优点:

  • 组合模式使得客户端代码可以一致地处理对象和对象容器,无需关系处理的单个对象,还是组合的对象容器。
  • 将”客户代码与复杂的对象容器结构“解耦。
  • 可以更容易地往组合对象中加入新的构件。

组合模式的缺点:

  • 使得设计更加复杂。客户端需要花更多时间理清类之间的层次关系。(这个是几乎所有设计模式所面临的问题)。

示例代码如下:

#include <iostream>
#include <vector>
using namespace std;

/* 抽象基类,定义了各种virtual操作接口,用于子类继承
 弊端:客户端对叶节点和枝节点是一致的,但叶节点并不具备Add和Remove的功能,因而对它们的实现是没有意义的
*/
class Component 
{
public:
    virtual void Operation() { }

    virtual void Add(const Component& com) { }

    virtual void Remove(const Component& com) { }

    virtual Component* GetChild(int index)
    {
        return 0;
    }

    virtual ~Component() { }
};

/* 树枝,叶子节点的集合 */
class Composite :public Component 
{
public:
    void Add(Component* com)
    {
        _coms.push_back(com);
    }

    void Operation() 
    {
        /* 遍历树枝中所有的叶子,并执行各叶子节点的Operation()函数 */
        for (std::vector<Component*>::iterator it = _coms.begin();it != _coms.end();it++)
        {
            (*it)->Operation();
        }
    }

    void Remove(Component* com) 
    {  
        //_coms.erase(&com);
    }

    Component* GetChild(int index) 
    {
        return _coms[index];
    }

private:
    std::vector<Component*> _coms;
};

class Leaf :public Component 
{
public:
    void Operation() 
    {
        cout << "Leaf::Operation..." << endl;
    }
};


int main() 
{
    Leaf *leaf = new Leaf();
    leaf->Operation();
    Composite *com = new Composite();
    com->Add(leaf);
    com->Operation();
    Component *leaf_ = com->GetChild(0);
    leaf_->Operation();

    delete leaf;
    delete com;

    return 0;
}

运行结果如下:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Chiang木

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值