意圖:將對象組成樹狀結(jié)構(gòu)以表示“部分-整體”的層次結(jié)構(gòu),使得Client對單個(gè)對象和組合對象的使用具有一致性。
上下文:在樹型結(jié)構(gòu)的問題中,Client必須以不同的方式處理單個(gè)對象和組合對象。能否提供一種封裝,統(tǒng)一簡單元素和復(fù)雜元素的概念,讓對象容器自己來實(shí)現(xiàn)自身的復(fù)雜結(jié)構(gòu),讓Client可以像處理簡單元素一樣來處理復(fù)雜元素,從而使Client與復(fù)雜元素的內(nèi)部結(jié)構(gòu)解耦?
UML
Component:為Composite中的對象聲明接口;在適當(dāng)情況下,實(shí)現(xiàn)所有類公共接口的默認(rèn)行為;聲明一個(gè)接口,用于訪問和管理Component的子部件;在遞歸結(jié)構(gòu)中定義一個(gè)接口,用于訪問一個(gè)父部件,并在適當(dāng)?shù)那闆r下實(shí)現(xiàn)它。
Leaf:在Composite中表示葉子對象。
Composite:存儲子部件,并定義有子部件的那些部件的行為。
Client:通過Component接口操作Composite的對象。文章來源:http://www.zghlxwxcb.cn/news/detail-731304.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-731304.html
代碼:
#include <iostream>
#include <list>
using namespace std;
class Component
{
public:
string name;
Component(string name):name(name){
}
virtual void add(Component *c) = 0;
virtual void remove(Component *c) = 0;
virtual void display(int depth) = 0;
};
class Leaf:public Component
{
public:
// Component interface
Leaf(string name):Component(name){
}
public:
void add(Component *c);
void remove(Component *c);
void display(int depth);
};
void Leaf::add(Component *c )
{
(void)(c);//消除警告
cout << "不能向葉子中添加Component" << endl;
}
void Leaf::remove(Component *c)
{
(void)(c);//Warning
cout << "不能從葉子中刪除Component" << endl;
}
void Leaf::display(int depth)
{
cout << string(depth,'-') << this->name << endl;
}
class Composite:public Component
{
public:
list<Component*> children;
// Component interface
Composite(string name):Component(name){
}
public:
void add(Component *c);
void remove(Component *c);
void display(int depth);
};
void Composite::add(Component *c)
{
children.push_back(c);
}
void Composite::remove(Component *c)
{
children.remove(c);
}
void Composite::display(int depth)
{
cout << string(depth,'-') << this->name << endl;
list<Component*>::iterator it;
for(it = children.begin();it != children.end();it++){
Component *c = *it;
c->display(depth + 2);
}
}
int main()
{
Composite *root = new Composite("樹干");
root->add(new Leaf("樹葉1"));
root->add(new Leaf("樹葉2"));
Composite *c1 = new Composite("樹枝1");
c1->add(new Leaf("樹葉1-1"));
c1->add(new Leaf("樹葉1-2"));
root->add(c1);
Composite *c1_1 = new Composite("樹枝1-1");
c1_1->add(new Leaf("樹葉1-1-1"));
c1_1->add(new Leaf("樹葉1-1-2"));
c1->add(c1_1);
root->add(new Leaf("樹葉3"));
root->display(1);
return 0;
}
結(jié)果
-樹干
---樹葉1
---樹葉2
---樹枝1
-----樹葉1-1
-----樹葉1-2
-----樹枝1-1
-------樹葉1-1-1
-------樹葉1-1-2
---樹葉3
到了這里,關(guān)于19.組合模式(Composite)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!