组合模式,又称合成模式,部分-整体模式(part-whole)
Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.(将对象组合成树形结构以表示“部分-整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。)
UML类图
C++代码实现
#include <iostream>
#include <vector>
using namespace std;
class Component {
public:
virtual void Operation()=0;// { cout << "call Component::Operation()" << endl; }
};
class Composite : public Component {
public:
void Operation() {
cout << "call Composite::Operation()" << endl;
typedef vector<Component*>::iterator VectIter;
for (VectIter iter=_VectCom.begin(); iter!=_VectCom.end(); ++iter) {
(*iter)->Operation();
}
}
void AddItem(Component* comp) { _VectCom.push_back(comp); }
void RemoveItem(Component* comp) { /*未实现*/ }
Component* GetChild(int index) { return _VectCom[index]; }
private:
vector<Component*> _VectCom;
};
class Leaf : public Component {
public:
void Operation() { cout << "call Leaf::Operation()" << endl; }
};
#include "Composite.h"
int main()
{
Leaf* I = new Leaf();
I->Operation();
Composite* II = new Composite();
II->AddItem(I);
II->Operation();
Component* III = II->GetChild(0);
III->Operation();
delete II;
delete I;
return 0;
}组合模式是对DIP原则的破坏。另外,组合模式具有安全模式和透明模式2种。本实现是安全模式
Composite模式通过和Decorator模式有着类似的结构图,但是Composite模式旨在构造类,而 Decorator模式重在不生成子类即可给对象添加职责。Decorator模式重在修饰,而Composite模式重在表示。
本文深入探讨了组合模式的概念及其在软件设计中的应用,通过UML类图和C++代码实现展示了如何利用组合模式构建树形结构来表示部分-整体的层次关系,以及其在保持代码一致性方面的优势。
1820

被折叠的 条评论
为什么被折叠?



