模式动机(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。缺点是设计更加复杂了,而且一般只适用于树状分层的关系。