组合模式(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;
}

运行结果如下: