9 结构型模式-----组合模式

模式动机(Composite Pattern)将对象组合成树形结构来表示“整体-部分”层次。操作时,使得对部分的操作与对整体的操作具有一致性。

模式结构图:

 

典型的Composite结构为:

模式代码:

bt_组合模式.h

 1 #ifndef CP_H
 2 #define CP_H
 3 #include <iostream>
 4 #include <vector>
 5 using namespace std;
 6 
 7 /*
 8     抽象部件类
 9 */
10 class Composite;
11 class Component
12 {
13 public:
14     virtual ~Component(){ }
15     virtual void Add(Component* pc) = 0;
16     virtual void Remove(Component* pc) = 0;
17     virtual Component* GetChild(unsigned int i) = 0;
18     virtual void Operation() = 0;               // 一致的操作接口
19 
20 };
21 
22 /*
23     组合容器类,其中既可以放组合器,又可以放叶子结点
24 */
25 class Composite : public Component
26 {
27 public:
28     virtual void Add(Component* pc)
29     {
30         this->children.push_back(pc);
31     }
32     virtual void Remove(Component* pc)
33     {
34         cout << "删除部件" << endl;
35     }
36     virtual Component* GetChild(unsigned int i)
37     {
38         if(i < this->children.size())
39             return this->children[i];
40         else
41             return NULL;
42     }
43     virtual void Operation()
44     {
45         cout << "执行容器的相应操作" << endl;
46         vector<Component*>::iterator iter = this->children.begin();
47         for(; iter != this->children.end(); iter++)
48             (*iter)->Operation();
49     }
50 
51 private:
52     vector<Component*> children;
53 };
54 
55 /*
56     叶子结点类
57 */
58 class Leaf : public Component
59 {
60 public:
61     virtual void Add(Component* pc)
62     {
63         cerr << "操作错误" << endl;
64         return ;
65     }
66     virtual void Remove(Component* pc)
67     {
68         cerr << "操作错误" << endl;
69         return ;
70     }
71     virtual Component* GetChild(unsigned int i)
72     {
73         cout << "操作错误" << endl;
74         return NULL;
75     }
76     virtual void Operation()
77     {
78         cout << "执行叶子的相应操作" << endl;
79     }
80 };
81 
82 #endif // CP_H

 

测试用例.cpp

 1 #include "bt_组合模式.h"
 2 
 3 int main()
 4 {
 5     cout << "***** 组合模式测试 *****" << endl;
 6     Component* pC = new Composite;
 7     Composite* pS = new Composite;
 8     Leaf* pL1 = new Leaf;
 9     Leaf* pL2 = new Leaf;
10 
11     pC->Add(pL1);
12     pS->Add(pL2);
13     pC->Add(pS);
14     pC->Operation();
15 
16     cout << endl;
17     pL1->Add(pL2);
18 
19     delete pL2;
20     delete pL1;
21     delete pS;
22     delete pC;
23 
24     return 0;
25 }

 

模式优缺点:

客户端可以使用一致的方法操作对象,无论该对象是Leaf还是Composite。缺点是设计更加复杂了,而且一般只适用于树状分层的关系。

 

 

 

 

原文地址:https://www.cnblogs.com/benxintuzi/p/4547611.html