C++组合模式

来源:互联网 发布:linux系统如何使用 编辑:程序博客网 时间:2024/05/16 08:08
#include "stdafx.h"#include<iostream>#include<string>#include<vector>using namespace std;class Component{public:string m_strName;Component(string strName){this->m_strName = strName;}virtual void add(Component *com) = 0;virtual void dispaly(int nDepth) = 0;};class Leaf :public Component{public:Leaf(string strName) :Component(strName) {/*this->m_strName=strName;*/ }virtual void add(Component *com) {cout << "can't add leaf" << endl;}virtual void dispaly(int nDepth){string strTemp;for (int i = 0; i < nDepth; i++){strTemp += "-";}strTemp += this->m_strName;cout << strTemp << endl;}};class Composite :public Component{public:Composite(string strName) :Component(strName) {}virtual void add(Component *com) { m_pCom.push_back(com); }virtual void dispaly(int nDepth){string strTemp;for (int i = 0; i < nDepth; i++){strTemp += "-";}strTemp += this->m_strName;cout << strTemp << endl;vector<Component*>::iterator it = m_pCom.begin();while (it != m_pCom.end()){(*it)->dispaly(nDepth + 2);++it;}}private:vector<Component*>m_pCom;};void main(){Composite *p = new Composite("总经理");Composite *pM = new Composite("技术部门经理");p->add(pM);pM->add(new Leaf("开发人员A"));pM->add(new Leaf("开发人员B"));Composite *pS = new Composite("销售部门经理");p->add(pS);pS->add(new Leaf("销售人员C"));pS->add(new Leaf("销售人员D"));p->dispaly(1);};

0 0
原创粉丝点击