在开发时,如果遇到使用递归构建树状的组合结构,那么可以考虑使用Composite模式.Composite模式将对象组合成树形结构,来表示部分,整体的层次结构.
解决整合与部分可以被一致对待问题。
其类结构如图所示:
在Component中声明可所有管理子类对象的方法,因此实现Component接口的子类都有了Add,Remove等功能,这样叶子节点和枝节点对于外界没有区别;但是因为Leaf类本身不具备Add,Remove等功能,实现也没有意义.
在实现时,管理叶子节点需要容器,这里使用了vector.
//Component.h
//Component.h
#ifndef _COMPONENT_H_
#define _COMPONENT_H_
class Component
{
public:
Component();
virtual ~Component();
virtual void Operation() = 0;
virtual void Add(const Component&);
virtual void Remove(const Component&);
virtual Component* GetChild(int);
};
#endif
//Component.cpp
//Component.cpp
#include"Component.h"
Component::Component(){}
Component::~Component(){}
void Component::Add(const Component& com)
{}
void Component::Remove(const Component& com)
{}
Component* Component::GetChild(int index)
{
return 0;
}
//Composite.h
//Composite.h
#ifndef _COMPOSITE_H_
#define _COMPOSITE_H_
#include"Component.h"
#include<vector>
class Composite :public Component
{
public:
Composite();
~Composite();
void Operation();
void Add(Component* com);
void Remove(Component* com);
Component* GetChild(int index);
private:
std::vector<Component*> comVec;
};
#endif
//Composite.cpp
//Composite.cpp
#include"Component.h"
#include"Composite.h"
Composite::Composite()
{
}
Composite::~Composite()
{
}
void Composite::Operation()
{
std::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)
{
std::vector<Component*>::iterator comIter = comVec.begin();
for (; comIter != comVec.end(); comIter++)
{
if (*comIter == com)
{
comVec.erase(comIter);
return;
}
}
}
Component* Composite::GetChild(int index)
{
return comVec[index];
}
//Leaf.h
//Leaf.h
#ifndef _LEAF_H_
#define _LEAF_H_
#include"Component.h"
class Leaf :public Component
{
public:
Leaf();
~Leaf();
void Operation();
};
#endif
//Leaf.cpp
//Leaf.cpp
#include"Leaf.h"
#include<iostream>
Leaf::Leaf()
{}
Leaf::~Leaf()
{}
void Leaf::Operation()
{
std::cout << "Leaf operation..." << std::endl;
}
//main.cpp
//main.cpp
#include"Component.h"
#include"Composite.h"
#include"Leaf.h"
int main()
{
Leaf* l = new Leaf();
l->Operation();
Composite *com = new Composite();
com->Add(l);
com->Operation();
Component* ll = com->GetChild(0);
ll->Operation();
return 0;
}