开发设计模式设计模式之composite模式
Hoshea Zhang组合模式又称:对象树(Object Tree)是一种结构型设计模式,可以使用它将对象组合成树状结构,并且能像使用独立对象一样使用它们。
- 组件(Component):定义组合模式中所有对象共有的方法和属性。
- 叶子节点(Leaf):叶子节点对象,也是组合中没有子节点的对象。
- 组合节点(Composite):表示组合中的容器对象,该对象包含其他子节点。
实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
| #include <iostream> #include <list> #include <memory> #include <utility> #include <cstddef> using namespace std; class Company { public: Company(string name) { m_name = name; } virtual ~Company() {} virtual void Add(std::unique_ptr<Company>) {} virtual void Show(int depth) {} protected: string m_name; };
class ConcreteCompany : public Company { public: ConcreteCompany(string name) : Company(name) {} virtual ~ConcreteCompany() { for (auto& company : m_listCompany) { company.reset(nullptr); } } void Add(std::unique_ptr<Company> pCom) { m_listCompany.push_back(std::move(pCom)); } void Show(int depth) { for (int i = 0; i < depth; i++) cout << "-"; cout << m_name << endl; auto iter = m_listCompany.begin(); for (; iter != m_listCompany.end(); iter++) (*iter)->Show(depth + 2); } private: list<std::unique_ptr<Company>> m_listCompany; };
class FinanceDepartment : public Company { public: FinanceDepartment(string name) :Company(name) {} virtual ~FinanceDepartment() {} virtual void Show(int depth) { for (int i = 0; i < depth; i++) cout << "-"; cout << m_name << endl; } };
class HRDepartment :public Company { public: HRDepartment(string name) :Company(name) {} virtual ~HRDepartment() {} virtual void Show(int depth) { for (int i = 0; i < depth; i++) cout << "-"; cout << m_name << endl; } }; int main() { auto root = std::make_unique<ConcreteCompany>("总公司"); auto leaf1 = std::make_unique < FinanceDepartment>("总公司财务部"); auto leaf2 = std::make_unique < HRDepartment>("总公司人力资源部"); root->Add(std::move(leaf1)); root->Add(std::move(leaf2)); auto mid1 = std::make_unique < ConcreteCompany>("杭州分公司"); auto leaf3 = std::make_unique < FinanceDepartment>("杭州分公司财务部"); auto leaf4 = std::make_unique < HRDepartment>("杭州分公司人力资源部"); mid1->Add(std::move(leaf3)); mid1->Add(std::move(leaf4)); root->Add(std::move(mid1)); auto mid2 = std::make_unique < ConcreteCompany>("上海分公司"); auto leaf5 = std::make_unique < FinanceDepartment>("上海分公司财务部"); auto leaf6 = std::make_unique < HRDepartment>("上海分公司人力资源部"); mid2->Add(std::move(leaf5)); mid2->Add(std::move(leaf6)); root->Add(std::move(mid2)); root->Show(0); return 0; }
|