組合模式(Composite Pattern)—— 將對象組合成樹形結構以表示"部分-總體"的層次結構。組合模式使得用戶對單個對象和組合對象的使用具備一致性。ios
問題:在開發中,咱們常常可能要遞歸構建樹狀的組合結構,Composite 模式則提供了很好的解決方案。c++
主要解決:它在咱們樹型結構的問題中,模糊了簡單元素和複雜元素的概念,客戶程序能夠向處理簡單元素同樣來處理複雜元素,從而使得客戶程序與複雜元素的內部結構解耦。ui
什麼時候使用:spa
如何解決:樹枝和葉子實現統一接口,樹枝內部組合該接口。code
關鍵代碼:樹枝內部組合該接口,而且含有內部屬性 List,裏面放 Component。對象
使用場景:部分、總體場景,如樹形菜單,文件、文件夾的管理。遞歸
#include<iostream>
#include<vector>
#include<string>
using namespace std;
//接口抽象
class Component {
public:
Component(string name){
m_name=name;
}
virtual ~Component(){}
public:
virtual void Operation()=0;
virtual void Add(const Component& ){}
virtual void Remove(const Component& ){}
virtual Component* GetChild(int ){
return NULL;
}
string m_name;
};
class Composite:public Component
{
public:
Composite(string name):Component(name){}
~Composite(){
cout<<m_name<<" destructor..."<<endl;
for (vector<Component *>::iterator it = comVec.begin();it!=comVec.end();++it){
delete *it;
}
}
public:
void Operation(){
vector<Component*>::iterator comiter=comVec.begin();
for (; comiter!=comVec.end();comiter++)
{
(*comiter)->Operation();
}
}
void Add(Component* com){
comVec.push_back(com);
}
void Remove(Component* com){
for (vector<Component*>::iterator it = comVec.begin();it!=comVec.end();it++){
if (*it == com){
delete *it;
*it=NULL;
comVec.erase(it);
break;
}
}
}
Component* GetChild(int index){
return comVec[index];
}
private:
vector<Component*> comVec;
};
class Leaf:public Component
{
public:
Leaf(string name):Component(name){
}
~Leaf(){
cout<<m_name<<" destructor..."<<endl;
}
void Operation(){
cout<<"Leaf("<<m_name<<") operation......"<<endl;
}
};
int main() {
Composite* root = new Composite("root");
Leaf* la=new Leaf("leaf a");
Leaf* lb=new Leaf("leaf b");
Leaf* laa=new Leaf("leaf aa");
Composite* coma = new Composite("com a");
Composite* comb = new Composite("com b");
coma->Add(la);
coma->Add(lb);
comb->Add(laa);
root->Add(coma);
root->Add(comb);
// coma->Operation();
root->Operation();
// Component* l_a=coma->GetChild(0);
// l_a->Operation();
delete root;
return 0;
}
複製代碼