组合模式

来源:互联网 发布:高中历史辅助教材淘宝 编辑:程序博客网 时间:2024/05/17 03:44

组合模式是结构型模式的一种,组合模式中,通过将对象组合成树形结构以表示部分-整体的层次结构,使得用户对单个模式和组合对象的使用具有一致性。

组合模式让客户端不再区分操作的是组合对象还是叶子对象,而是以一种统一的方式来操作,组合模式的结构类似于树形结构,容器对象和子对象的结构组合形成一个对象树,客户对树枝对象的操作不只调用树枝对象采取相应的操作,树枝对象还会调用子对象的相应的函数,一直这样传递下去直到叶子节点,可见这个数的递归操作的思想是一样的。


组合模式的UML图:


如上图所示,组合模式涉及到三个角色:

抽象构件(Component):是一个抽象构件,给出了组合中树叶构件(Leaf)和树枝构件(Composite)的所有接口

树叶构件(Leaf):树叶没有下级子对象,实现了Component中定义的接口,对于add,remove,getChild等管理子对象的操作,树叶构件给出一个象征意义的实现

树枝构件(Composite):分支节点对象,含有子对象,实现了Component中的接口,Composite的operation操作中不仅负责执行本职的operation操作,同时也要负责子对象中operation的调用

C++示例代码:

class Component{public:virtual ~Component(){}virtual void operation() = 0;  void add(Component*component){}void Remove(Component* component){}Component* getChild(int index){}protected:Component(){}};class Leaf :public Component{public:Leaf(){}~Leaf(){}virtual void operation(){cout << "Leaf operation" << endl;}void add(Component* component){cout << "Leaf object operation not support" << endl;}void Remove(Component* component){cout << "Leaf object operation not support" << endl;}Component* getChild(int index){cout << "Leaf object operation not support" << endl;return NULL;}};class Composite :public Component{public:Composite(){}~Composite(){}void add(Component* component){list<Component*>::iterator iter;for (iter = children.begin(); iter != children.end(); iter++)if (*iter == component)break;if (iter == children.end())children.push_back(component);}void remove(Component* component){list<Component*>::iterator iter;for (iter = children.begin(); iter != children.end(); iter++)if (*iter == component)children.erase(iter);}Component* getChild(int index){list<Component*>::iterator iter;for (iter = children.begin(); iter != children.end(); iter++){if (index == 0){return *iter;}index--;}if (iter == children.end())return NULL;}void operation(){cout << "composite operation" << endl;list<Component*>::iterator iter;for (iter = children.begin(); iter != children.end(); iter++)(*iter)->operation();}private:list<Component*> children;};






0 0
原创粉丝点击