C++组合模式
<上一节
下一节>
由遇到的问题引出组合模式
在开发中,我们经常可能要递归构建树状的组合结构,组合模式则提供了很好的解决方案。模式选择
组合模式的典型结构图为:图 2-1:组合Pattern 结构图
组合模式的实现
完整代码示例(code):组合模式的实现很简单,这里为了方便初学者的学习和参考,将给出完整的实现代码(所有代码采用 C++实现,并在 VC 6.0 下测试运行)。代码片断 1:Component.h
//Component.h
#ifndef _COMPONENT_H_
#define _COMPONENT_H_
class Component{
public:
Component();
virtual ~Component();
public:
virtual void Operation() = 0;
virtual void Add(const Component& );
virtual void Remove(const Component& );
virtual Component* GetChild(int );
protected:
private:
};
#endif //~_COMPONENT_H_
代码片断 2:Component.cpp
//Component.cpp
#include "Component.h"
Component::Component(){
}
Component::~Component(){
}
void Component::Add(const Component& com){
}
Component* Component::GetChild(int index){
return 0;
}
void Component::Remove(const Component& com){
}
代码片断 3:Composite.h
//Composite.h
#ifndef _COMPOSITE_H_
#define _COMPOSITE_H_
#include "Component.h"
#include <vector>
using namespace std;
class Composite:public Component{
public:
Composite();
~Composite();
public:
void Operation();
void Add(Component* com);
void Remove(Component* com);
Component* GetChild(int index);
protected:
private:
vector<Component*> comVec;
};
#endif //~_COMPOSITE_H_
代码片断 4:Composite.cpp
//Composite.cpp
#include "Composite.h"
#include "Component.h"
#define NULL 0
//define NULL POINTOR
Composite::Composite(){
//vector<Component*>::iterator itend = comVec.begin();
}
Composite::~Composite(){
}
void Composite::Operation(){
vector<Component*>::iterator comIter = comVec.begin();
for (;comIter != comVec.end();comIter++){
(*comIter)->Operation();
}
}
void Composite::Add(Component* com){
comVec.push_back(com);
}
void Composite::Remove(Component* com){
comVec.erase(&com);
}
Component* Composite::GetChild(int index){
return comVec[index];
}
代码片断 5:leaf.h
//Leaf.h
#ifndef _LEAF_H_
#define _LEAF_H_
#include "Component.h"
class Leaf:public Component{
public:
Leaf();
~Leaf();
void Operation();
protected:
private:
};
#endif //~_LEAF_H_
代码片断 6:leaf.cpp
//Leaf.cpp
#include "Leaf.h"
#include <iostream>
using namespace std;
Leaf::Leaf(){
}
Leaf::~Leaf(){
}
void Leaf::Operation(){
cout<<"Leaf operation....."<<endl;
}
代码片断 7:main.cpp
//main.cpp
#include "Component.h"
#include "Composite.h"
#include "Leaf.h"
#include <iostream>
using namespace std;
int main(int argc,char* argv[]){
Leaf* l = new Leaf();
l->Operation();
Composite* com = new Composite();
com->Add(l);
com->Operation();
Component* ll = com->GetChild(0);
ll->Operation();
return 0;
}
代码说明:组合模式在实现中有一个问题就是要提供对于子节点(Leaf)的管理策略,这里使用的是 STL 中的 vector,可以提供其他的实现方式,如数组、链表、Hash 表等。
关于组合模式的讨论
组合模式通过和装饰模式有着类似的结构图,但是组合模式旨在构造类,而 Decorator 模式重在不生成子类即可给对象添加职责。装饰模式重在修饰,而组合模式重在表示。
<上一节
下一节>