1.描述
将一种对象组合成树状层次结构的模式。
2.优点
1)对树上的对象处理一致。
2)可以容易在组合内加入新的对象,而不改源代码
3.缺点
1)对树的逻辑需要树立清楚。
2)不容易使用继承的方法增加功能。
4.结构
1)抽象构件:树叶和树枝的抽象类。
2)树叶构件:没有子节点。
3)树枝构件:管理树叶构件。
5.UML
6.示例
#include "stdafx.h"
#include <iostream>
#include <Set>
#include <Vector>
//1.抽象构件
class Component
{
public:
Component(std::string name)
{
_Name = name;
}
virtual void Add(Component * c) {};
virtual void Remove(Component * c) {};
virtual void Display(int depth) = 0;//显示打印
virtual void LineOfDuty() = 0;//履行职责
protected:
std::string _Name;
};
//2.叶子构件
class HRDepartment:public Component
{
public:
HRDepartment(std::string name)
:Component(name)
{
}
virtual void Display(int depth)
{
for (int i = 0;i<depth;i++)
{
std::cout << "-";
}
std::cout << _Name.c_str()<<std::endl;
};//显示打印
virtual void LineOfDuty()
{
std::cout << _Name.c_str() << "员工招聘培新管理" << std::endl;
};//履行职责
};
class FinanceDepartment :public Component
{
public:
FinanceDepartment(std::string name)
:Component(name)
{
}
virtual void Display(int depth)
{
for (int i = 0; i<depth; i++)
{
std::cout << "-";
}
std::cout << _Name.c_str() << std::endl;
};//显示打印
virtual void LineOfDuty()
{
std::cout << _Name.c_str() << "公司财务收支管理" << std::endl;
};//履行职责
};
//3.树枝构件
class Company :public Component
{
public:
Company(std::string name)
:Component(name)
{
}
virtual void Add(Component * c)
{
_Children.push_back(c);
};
virtual void Remove(Component * c)
{
auto it = std::find(_Children.begin(), _Children.end(),c);
if (it != _Children.end())
{
_Children.erase(it);
}
};
virtual void Display(int depth)
{
for ( int i = 0;i < depth;i++)
{
std::cout << "-";
}
std::cout << _Name.c_str()<<std::endl;
for (auto c = _Children.begin(); c != _Children.end();c++)
{
(*c)->Display(depth + 2);
}
};
virtual void LineOfDuty()
{
for (auto c = _Children.begin(); c != _Children.end(); c++)
{
(*c)->LineOfDuty();
}
};//履行职责
private:
std::vector<Component * > _Children;
};
int main()
{
Company * root = new Company("北京总公司");
root->Add(new HRDepartment("总公司人力资源部"));
root->Add(new FinanceDepartment("总公司人力资源部"));
Company * c1= new Company("石家庄分公司");
c1->Add(new HRDepartment("石家庄分公司人力资源部"));
c1->Add(new FinanceDepartment("石家庄分公司人力资源部"));
root->Add(c1);
std::cout << "结构图" << std::endl;
root->Display(1);
std::cout << "职责" << std::endl;
root->LineOfDuty();
getchar();
return 0;
}
结构图
-北京总公司
---总公司人力资源部
---总公司人力资源部
---石家庄分公司
-----石家庄分公司人力资源部
-----石家庄分公司人力资源部
职责
总公司人力资源部员工招聘培新管理
总公司人力资源部公司财务收支管理
石家庄分公司人力资源部员工招聘培新管理
石家庄分公司人力资源部公司财务收支管理