组合模式:又叫部分整体模式,属于结构型模式。
基本原理:以树形的结构将相似的对象组合起来。
主要流程:
1.创建对象
2.在对象中设置用来存放下一级相似对象的数据结构。
3.在对象中设置增删改查等功能。
注意:这种模式和数据结构中的树形结构相似
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Employee
{
private:
string name;
string dept;
string salary;
vector<Employee*> subordinates;
public:
Employee(){}
Employee(string name,string dept,string salary):name(name),dept(dept),salary(salary)
{
this->subordinates = vector<Employee*>();
}
void add(Employee* e)
{
this->subordinates.push_back(e);
}
void removeSub(Employee *e)
{
vector<Employee*>::iterator it;
for (it = subordinates.begin(); it != subordinates.end(); ++it)
{
if (e->getName() == (*it)->getName())
{
subordinates.erase(it);
break;
}
}
}
vector<Employee*> getSubordinates()
{
return subordinates;
}
string getName()
{
return name;
}
string tostring()
{
return "Employee :[ Name : " + name + ", dept : " + dept + ", salary : "+ salary + " ]";
}
};
int main()
{
Employee * CEO = new Employee("ll","CEO","30000");
Employee *headSales = new Employee("aa","Head Sales","20000");
Employee *headMarketing = new Employee("Michel","Head Marketing", "20000");
Employee *clerk1 = new Employee("Laura","Marketing", "10000");
Employee *clerk2 = new Employee("Bob","Marketing", "10000");
Employee *salesExecutive1 = new Employee("Richard","Sales", "10000");
Employee *salesExecutive2 = new Employee("Rob","Sales", "10000");
Employee *salesExecutive3 = new Employee("Rob2","Sales", "10000");
CEO->add(headSales);
CEO->add(headMarketing);
headSales->add(salesExecutive1);
headSales->add(salesExecutive2);
headSales->add(salesExecutive3);
headMarketing->add(clerk1);
headMarketing->add(clerk2);
cout<<CEO->tostring()<<endl;
for (size_t i = 0; i < CEO->getSubordinates().size() ;++i)
{
Employee * emp = CEO->getSubordinates().at(i);
cout<<emp->tostring()<<endl;
vector<Employee*> emp1 = emp->getSubordinates();
for (size_t i = 0; i < emp1.size() ;++i)
{
cout<<emp1.at(i)->tostring()<<endl;
}
}
return 0;
}