组合模式

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

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


组合模式的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;
	};






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值