土木工程毕设代做网站国外免费建站网站
组合模式
将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
适用场景
1、你想表示对象的部分 -整体层次结构。
2、你希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象。
采用菜鸟教程的例子,这里用C++实现
#include<iostream>
#include<string>
#include<list>using namespace std;//创建Employee类,该类带有Employee对象的列表。
class employee
{
public:employee(string tname, string tdept, int tsalary) { name = tname; dept = tdept; salary = tsalary; };~employee() {};void add(employee e) { subordinates.push_back(e); };void remove(employee e) { subordinates.remove(e); };string get_name() { return name; };string get_dept() {return dept;};int get_salary() { return salary; };list<employee> get_subordinates() { return subordinates; };void toString() { cout << "name: " << name << endl << "dept: " << dept << endl << "salary: " << salary << endl; };friend bool operator==(const employee &a, const employee &b);private:string name;string dept;int salary;list<employee> subordinates;
};bool operator==(const employee &a, const employee &b)
{if (a.name == b.name && a.dept == b.dept){return true;}else{return false;}
}int main()
{employee t1("Jhon", "CEO", 30000);employee t2("Robert", "Sales", 10000);employee t3("Michel", "Support", 10000);employee t4("Luara", "Market", 10000);employee t5("Bob", "Technique", 15000);t1.add(t2);t1.add(t3);t1.add(t4);t1.add(t5);t1.toString();cout << endl;list<employee> iy = t1.get_subordinates();list<employee>::iterator it;for (it = iy.begin(); it != iy.end(); ++it){(*it).toString();cout << endl;}return 0;
}
在visual studio 2015上运行结果: