將對象組合成樹形結構以表示“部分-整體”的層次結構。C o m p o s i t e使得用戶對單個對象和組合對象的使用具有一致性。
2. 動機
在繪圖編輯器和圖形捕捉系統這樣的圖形應用程序中,用戶可以使用簡單的組件創建複雜的圖表。用戶可以組合多個簡單組件以形成一些較大的組件,這些組件又可以組合成更大的組件。一個簡單的實現方法是爲Te x t和L i n e這樣的圖元定義一些類,另外定義一些類作爲這些圖元的容器類( C o n t a i n e r )。
然而這種方法存在一個問題:使用這些類的代碼必須區別對待圖元對象與容器對象,而實際上大多數情況下用戶認爲它們是一樣的。對這些類區別使用,使得程序更加複雜。
C o m p o s i t e模式描述瞭如何使用遞歸組合,使得用戶不必對這些類進行區別,如下圖所示。
C++舉例:
#ifndef COMPOSITE
#define COMPOSITE
#include <string>
#include <vector>
#include <iostream>
using std::string;
using std::vector;
using std::cout;
using std::endl;
class CFolder{
protected:
string m_strName;
public:
CFolder(string str) : m_strName(str) {}
virtual void Add(CFolder* pFolder){}
virtual void Remove(){}
virtual void Show(){cout<<m_strName<<endl;}
virtual void Display(){Show();}
};
class CConcreateFolder : public CFolder{
private:
vector<CFolder*> vFolderList;
public:
CConcreateFolder(string str) : CFolder(str){}
virtual void Add(CFolder* pFolder){
vFolderList.push_back(pFolder);
}
virtual void Display(){
for(vector<CFolder*>::iterator it=vFolderList.begin();it!=vFolderList.end();it++){
(*it)->Show();
}
cout<<endl;
}
};
class CTxt : public CFolder{
public:
CTxt(string str) : CFolder(str){}
};
class CPic : public CFolder{
public:
CPic(string str) : CFolder(str){}
};
class CMovie : public CFolder{
public:
CMovie(string str) : CFolder(str){}
};
#endif
#include <iostream>
#include "composite.h"
int main(){
CFolder* pRoot=new CConcreateFolder("MainDisk");
pRoot->Add(new CMovie("FastAndFurious.rmvb"));
pRoot->Add(new CTxt("Diary.txt"));
pRoot->Add(new CPic("Beauty.jpg"));
CFolder* pSub=new CConcreateFolder("Study");
pRoot->Add(pSub);
pSub->Add(new CTxt("Math.txt"));
pSub->Add(new CMovie("Teacher.mp4"));
pRoot->Show();
pRoot->Display();
pSub->Show();
pSub->Display();
return 0;
}