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; }