組合模式(Composite):將對象組合成樹狀結構以表示“整體-部分”階層,組合模式使得使用者對單個對象和組合對象的使用具有一致性。
UML類圖:
模式說明:
Component 是組合中的對象聲明介面,在適當的情況下,實現所有類共有介面的預設行為。聲明一個介面用於訪問和管理Component子組件。Leaf 在組合中表示葉子結點對象,葉子結點沒有子結點。Composite 定義有枝節點行為,用來儲存子組件,在Component介面中實現與子組件有關操作,如增加(add)和刪除(remove)等。以下情況下適用Composite模式:1.你想表示對象的部分-整體階層2.你希望使用者忽略組合對象與單個對象的不同,使用者將統一地使用組合結構中的所有對象。基本代碼:
/********************************************************************filename: Composite.hcreated:2013-01-24author:firehoodpurpose:firehood 學設計模式之---組合模式*********************************************************************/#pragma once#include <iostream> #include <string>#include <list>using namespace std; // 組合對象(樹狀結構)class Component{public:Component(string name):m_strName(name){}virtual ~Component(void){}public:virtual void add(Component* pChild){}virtual void remove(Component* pChild){}virtual Component* getChild(int index){return NULL;}virtual void operation(int depth) = 0;protected:string m_strName;};// 葉子節點class Leaf : public Component{public:Leaf(string name):Component(name){}virtual ~Leaf(void){}public:virtual void operation(int depth){for(int i=0;i<depth;i++){cout<<"--";}cout<<m_strName<<endl;}};// 枝節點class Composite : public Component{public:Composite(string name):Component(name){m_ComponentList.clear();}virtual ~Composite(void){for(list<Component*>::iterator iter = m_ComponentList.begin(); iter != m_ComponentList.end(); iter++) { delete (*iter);} }public:virtual void add(Component *pChild){if(pChild != NULL){m_ComponentList.push_back(pChild);}} virtual void remove(Component* pChild){if(pChild == NULL) { m_ComponentList.remove(pChild);} }virtual Component* getChild(int index){list<Component*>::iterator iter; int i = 0;for(iter = m_ComponentList.begin(); iter != m_ComponentList.end(); iter++) { if(index == i++){return (*iter);}} return NULL;}virtual void operation(int depth){for(int i=0;i<depth;i++){cout<<"--";}cout<<m_strName<<endl;list<Component*>::iterator iter; for(iter = m_ComponentList.begin(); iter != m_ComponentList.end(); iter++) { (*iter)->operation(depth+1);} }private:list<Component*> m_ComponentList;};
用戶端調用代碼:
#include "Composite.h"#include <iostream>using namespace std;int main(int argc,char* argv[]){cout<<"*************************************"<<endl;cout<<"firehood 學設計模式之---組合模式"<<endl;cout<<"*************************************"<<endl; Composite root("root");root.add(new Leaf("Leaf A"));root.add(new Leaf("Leaf B"));Composite branch("branch A");branch.add(new Leaf("Leaf X")); branch.add(new Leaf("Leaf Y"));root.add(&branch); Composite branch2("branch B");branch2.add(new Leaf("Leaf X"));branch2.add(new Leaf("Leaf Y"));branch.add(&branch2);root.add(new Leaf("Leaf C"));root.operation(1); system("pause");return 0;}
執行結果:
*************************************
firehood 學設計模式之---組合模式
*************************************
--root
----Leaf A
----Leaf B
----branch A
------Leaf X
------Leaf Y
------branch B
--------Leaf X
--------Leaf Y
----Leaf C
請按任意鍵繼續. . .