2_6 CompositeMode.cpp 组合模式
生活随笔
收集整理的這篇文章主要介紹了
2_6 CompositeMode.cpp 组合模式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
// 定義:將對象組合成樹形結構以表示整體~部分的層次結構,
// 組合模式使得用戶對單個對象和組合對象具有一致性
//
// 模式舉例:總公司有財務部和技術員,分公司也有財務部和技術部
// 在總公司眼里分公司就是總公司的一個部門
//
// 模式特點:設計模式里唯一把對象整理成樹形的
//
//#include<iostream>
#include<string>
#include<vector>
using namespace std;//add的參數是string類型的還是Component類型的?
class Component
{
public:Component(string name):m_name(name){}virtual void add(Component *pComponent)=0;virtual void del(Component *pComponent)=0;virtual void showInfo()=0;protected:string m_name;
};class Leaf : public Component
{
public:Leaf(string name):Component(name){}virtual void add(Component *pComponent){cout <<"leaf can not add child";}virtual void del(Component *pComponent){cout <<"leaf can not del child";}virtual void showInfo(){cout <<"leaf node -- "<<m_name<<endl;}
};class Composite : public Component
{
public:Composite(string name):Component(name){}virtual void add(Component *pComponent){m_children.push_back(pComponent);}virtual void del(Component *pComponent){for(vector<Component*>::iterator iter=m_children.begin();iter!=m_children.end();iter++){if(*iter == pComponent){m_children.erase(iter);break;}}}virtual void showInfo(){cout <<"composite node -- "<<m_name<<endl;for(auto iter=m_children.begin();iter!=m_children.end();iter++){Composite *pComposite = dynamic_cast<Composite*>(*iter);Leaf *pLeaf = dynamic_cast<Leaf*>(*iter);if(pComposite != NULL){pComposite->showInfo();}else if(pLeaf != NULL){pLeaf->showInfo();}}}private:vector<Component*> m_children;
};int main()
{Composite * pZongGongSi = new Composite("總公司");Leaf * pZGSCaiWuBu = new Leaf("總公司財務部");pZongGongSi->add(pZGSCaiWuBu);Leaf * pZGSJiShuBu = new Leaf("總公司技術部");pZongGongSi->add(pZGSJiShuBu);Composite * pFenGongSi = new Composite("分公司");Leaf * pFGSCaiWuBu = new Leaf("分公司財務部");pFenGongSi->add(pFGSCaiWuBu);Leaf * pFGSJiShuBu = new Leaf("分公司技術部");pFenGongSi->add(pFGSJiShuBu);pZongGongSi->add(pFenGongSi);pZongGongSi->showInfo();return 0;
}
?
總結
以上是生活随笔為你收集整理的2_6 CompositeMode.cpp 组合模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 1_2 AbstractFactoryM
- 下一篇: 2_4 FacadeMode.cpp 外