设计模式之组合模式

来源:互联网 发布:汽车电脑编程 编辑:程序博客网 时间:2024/06/16 00:28
       组合模式是一种对象结构型模式,一般用于树型结构中,其本质是定义一个抽象组件类,该组件既可以代表叶子对象也可以代表容器对象(容器可以包含叶子和容器),使用时无需知道操作对象是叶子还是容器,实现对容器和叶子的无差别化操作。对子容器的节点操作时,本质上使用了递归遍历。

如下图的树型结构,



组合模式:

以下代码在VS2012上编译通过

.h文件

class Conponent//抽象组件类{public :virtual void addchildren(Conponent* child_);//添加子节点virtual void removechildren(Conponent* child_);//删除子节点virtual Conponent* getchildren(int num_);//获取某个子节点virtual void method();//调用组件方法};class leafConponent: public Conponent//末节点类{public :void addchildren(Conponent* child_);void removechildren(Conponent* child_);Conponent* getchildren(int num_);void method();};class contentConponent:public Conponent//容器类{list<Conponent*> mConp;public:void addchildren(Conponent* child_);void removechildren(Conponent* child_);Conponent* getchildren(int num_);void method();};

.cpp文件

void Conponent::addchildren(Conponent* child_){}void Conponent::removechildren(Conponent* child_){}Conponent* Conponent::getchildren(int num_){return NULL ;}void Conponent::method(){}void leafConponent::addchildren(Conponent* child_){cout<<"I can not add child"<<endl;}void leafConponent::removechildren(Conponent* child_){cout<<"I can not remove child"<<endl;}Conponent* leafConponent::getchildren(int num_){cout<<"I can not get child"<<endl;return NULL ;}void leafConponent::method(){cout<<"call leafConponent method"<<endl;}void contentConponent::addchildren(Conponent* child_){mConp.push_back(child_);cout<<"call contentConponent add child"<<endl;}void contentConponent::removechildren(Conponent* child_){mConp.pop_back();cout<<"call contentConponent remove child"<<endl;}Conponent* contentConponent::getchildren(int num_)//获取该容器下第num_个组件{cout<<"call contentConponent get child"<<endl;list<Conponent*>::iterator mlist=mConp.begin();advance(mlist,num_);return *mlist;}void contentConponent::method()//递归遍历该容器下所有组件的方法{cout<<"call contentConponent method"<<endl;list<Conponent*>::iterator i;for(i=mConp.begin();i!=mConp.end();i++){(*i)->method();}}

调用代码:

int _tmain(int argc, _TCHAR* argv[]){Conponent* leaf1=new leafConponent();//创建叶子节点1Conponent* leaf2=new leafConponent();//创建叶子节点2Conponent* leaf3=new leafConponent();//创建叶子节点3Conponent* cont1=new contentConponent();//创建容器1Conponent* cont2=new contentConponent();//创建容器2cont1->addchildren(leaf1);//在容器1中添加叶子节点1cont1->addchildren(leaf2);//在容器1中添加叶子节点2cont2->addchildren(leaf3);//在容器2中添加叶子节点3cont2->addchildren(cont1);//在容器2中添加容器1cont2->method();//执行容器2中各节点的方法return 0;}

执行结果:



1 0
原创粉丝点击