组合模式就是把子类继承关系搞成树形结构,类似于组织结构图,体现整体与部分的关系。
以下代码定义节点抽象类,整个树的节点都继承此类。
#include <iostream>
#include <vector>
using namespace std;
class Node
{
public:
int Level;
Node():Level(0){}
virtual ~Node(){};
virtual void Operation()=0;
virtual void Add(Node* component)=0;
virtual void Remove(Node* component)=0;
virtual Node* GetChild(int index)=0;
};
以下代码定义了叶子节点类,它不能添加子节点,只能被添加为子节点。
class Leaf:public Node
{
public:
void Operation()
{
cout<<"level="<<Level<<","<<__PRETTY_FUNCTION__<<endl<<endl;
}
void Add(Node* component){}
void Remove(Node* component){}
Node* GetChild(int index){return nullptr;}
};
以下代码定义了中间节点类,中间节点可以添加子节点。
class Composite:public Node
{
private:
vector<Node*> m_pChildren;
public:
void Operation()
{
cout<<"level="<<Level<<","<<__PRETTY_FUNCTION__<<endl;
for (vector<Node*>::iterator it = m_pChildren.begin(); it != m_pChildren.end();++it)
{
if (*it != nullptr)
{
(*it)->Operation();
}
}
}
void Add(Node* component)
{
m_pChildren.push_back(component);
if (component->Level <= Level)
{
component->Level = Level + 1;
}
}
void Remove(Node* component)
{
for (vector<Node*>::iterator it = m_pChildren.begin(); it != m_pChildren.end();++it)
{
if (*it == component)
{
if (*it != nullptr)
{
delete *it;
}
m_pChildren.erase(it);
break;
}
}
}
Node* GetChild(int index)
{
if (index >= m_pChildren.size() || index < 0)
{
return nullptr;
}
return m_pChildren[index];
}
};
以下代码演示了组合模式,首先创建了“根、枝、叶”节点,然后连接它们,最后打印出他们的层级关系。
int main(void){
Node* root = new Composite();
Node* branch = new Composite();
Node* leaf = new Leaf();
root->Add(branch);
branch->Add(leaf);
root->Operation();
branch->Operation();
leaf->Operation();
delete root;
delete branch;
delete leaf;
return 0;
}```
输出
```python
level=0,virtual void Composite::Operation()
level=1,virtual void Composite::Operation()
level=2,virtual void Leaf::Operation()
level=1,virtual void Composite::Operation()
level=2,virtual void Leaf::Operation()
level=2,virtual void Leaf::Operation()
网友评论