24合成模式
1合成模式的核心內(nèi)容是:
略:
2狀態(tài)模式的作用:略。
3狀態(tài)模式具體描述
合成模式:合成模式將對象組織到樹結(jié)構(gòu)中,可以用來描述整體與部分的關(guān)系。
合成模式就是一個處理對象的樹結(jié)構(gòu)的模式。合成模式把部分與整體的關(guān)系用樹結(jié)構(gòu)表示出來。
合成模式使得客戶端把一個個單獨(dú)的成分對象和由他們復(fù)合而成的合成對象同等看待。
?
Mary今天過生日。“我過生日,你要送我一件禮物。”
嗯,好吧,去商店,你自己挑。”
“這件T恤挺漂亮,買,這條裙子好看,買,這個包也不錯,買
。”“喂,買了三件了呀,我只答應(yīng)送一件禮物的哦。
”“什么呀,T恤加裙子加包包,正好配成一套呀,小姐,麻煩你包起來。
”“……”,MM都會用Composite模式了,你會了沒有?
4合成模式類圖
5.代碼:
#include<iostream>
#include <vector>
#include <string>
using namespace std;
//合成模式:合成模式將對象組織到樹結(jié)構(gòu)中,可以用來描述整體與部分的關(guān)系。
//合成模式就是一個處理對象的樹結(jié)構(gòu)的模式。合成模式把部分與整體的關(guān)系用樹結(jié)構(gòu)表示出來。
//合成模式使得客戶端把一個個單獨(dú)的成分對象和由他們復(fù)合而成的合成對象同等看待。
//
//Mary今天過生日。“我過生日,你要送我一件禮物。”
//嗯,好吧,去商店,你自己挑。”
//“這件T恤挺漂亮,買,這條裙子好看,買,這個包也不錯,買
//。”“喂,買了三件了呀,我只答應(yīng)送一件禮物的哦。
//”“什么呀,T恤加裙子加包包,正好配成一套呀,小姐,麻煩你包起來。
//”“……”,MM都會用Composite模式了,你會了沒有?
//組件類
class Component
{
public:
??? //組件名稱
??? string name;
??? Component(string name)
??? {
??????? this->name = name;
??? }
??? //添加組件
??? virtual void add(Component *) = 0;
??? //刪除組件類
??? virtual void remove(Component *) = 0;
??? //顯示
??? virtual void display(int) = 0;
};
?
?
class Leaf :public Component
{
public:
??? Leaf(string name) :Component(name)
??? {}
??? void add(Component *c)
??? {
??????? cout << "leaf cannotadd"<< endl;
??? }
??? void remove(Component *c)
??? {
??????? cout << "leaf cannotremove"<< endl;
??? }
??? void display(int depth)
??? {
??????? string str(depth, '-');
??????? str += name;
??????? cout << str << endl;
??? }
};
?
class Composite :public Component
{
private:
??? vector<Component*> component;
public:
??? Composite(string name) :Component(name)
??? {}
??? void add(Component *c)
??? {
??????? component.push_back(c);
??? }
??? void remove(Component *c)
??? {
??????? vector<Component*>::iterator iter = component.begin();
??????? while (iter != component.end())
??????? {
??????????? if (*iter == c)
??????????? {
??????????????? component.erase(iter);
??????????? }
??????????? iter++;
??????? }
??? }
??? void display(int depth)
??? {
??????? string str(depth, '-');
??????? str += name;
??????? cout << str << endl;
?
??????? vector<Component*>::iterator iter = component.begin();
??????? while (iter != component.end())
??????? {
??????????? (*iter)->display(depth + 2);
??????????? iter++;
??????? }
??? }
};
?
//顯示了樹狀結(jié)構(gòu)
int main()
{
??? Component *p = new Composite("小李");
??? p->add(new Leaf("小王"));
??? p->add(new Leaf("小強(qiáng)"));
?
??? Component *sub = new Composite("小虎");
??? sub->add(new Leaf("小王"));
??? sub->add(new Leaf("小明"));
??? sub->add(new Leaf("小柳"));
?
??? p->add(sub);
??? p->display(0);
?
??? cout << "*******" << endl;
??? sub->display(2);
?
??? cin.get();
?
??? return 0;
}
運(yùn)行結(jié)果如下:
總結(jié)
 
                            
                        - 上一篇: 党的地方各级委员会全体会议选举常务委员会
- 下一篇: 1.C++异常处理
