1. 程式人生 > >C++設計模式之八:Composite(組合)

C++設計模式之八:Composite(組合)

一、意圖:

將物件組合成樹形結構以表示成“部分-整體”的層次結構;

二、類圖:

三、組成元素:

Component:頂層介面,用於訪問子元件;

Leaf:葉節點,沒有子節點;

Composite:用於儲存子節點;

四、程式碼實現:

#include <iostream>
#include <list>
#include <algorithm>
#include <stdlib.h>

class Component
{
public:
	Component()
	{

	}
	virtual void Operation()=0;

	virtual void Add(Component* pChild)
	{
		
	}
	virtual void Remove(Component* pChild)
	{

	}
	virtual Component* GetChild(int nIndex)
	{
		return NULL;
	}
};

class Leaf:public Component
{
public:
	Leaf()
	{

	}
	virtual void Operation()
	{
		std::cout<<"Operation by leaf!"<<std::endl;
	}
};

class Composite:public Component
{
private:
	std::list<Component*> m_ListOfComponent;
public:
	Composite()
	{

	}
	~Composite()
	{
		std::list<Component*>::iterator iter1,iter2,temp;
		for (iter1=m_ListOfComponent.begin(),iter2=m_ListOfComponent.end();iter1!=iter2;++iter1)
		{
			temp=iter1;
			delete(*temp);
		}
	}
	virtual void Operation()
	{
		std::cout << "Operation by Composite"<<std::endl;
		std::list<Component*>::iterator iter1, iter2;
		for(iter1=m_ListOfComponent.begin(), iter2 = m_ListOfComponent.end();iter1 != iter2;++iter1)
		{
			(*iter1)->Operation();
		}	
	}
	
	virtual void Add(Component* pChild)
	{
		m_ListOfComponent.push_back(pChild);
	}
	virtual void Remove(Component* pChild)
	{
		std::list<Component*>::iterator iter;
		iter=std::find(m_ListOfComponent.begin(),m_ListOfComponent.end(),pChild);
		if (m_ListOfComponent.end()!=iter)
		{
			m_ListOfComponent.erase(iter);
		}
	}
	virtual Component* GetChild(int nIndex)
	{
		if (nIndex<=0||nIndex>m_ListOfComponent.size())
		{
			return NULL;
		}
		std::list<Component*>::iterator iter1,iter2;
		int i;
		for (i=1,iter1=m_ListOfComponent.begin(),iter2=m_ListOfComponent.end();iter1!=iter2;++iter1,++i)
		{
			if (i==nIndex)
			{
				break;
			}
		}
		return *iter1;
	}
};

void main()
{
	Leaf* pLeaf1=new Leaf();
	Leaf* pLeaf2=new Leaf();
	
	Composite* pComposite=new Composite();
	pComposite->Add(pLeaf1);
	pComposite->Add(pLeaf2);
	pComposite->Operation();
	std::cout<<std::endl;
	pComposite->Remove(pLeaf1);
	pComposite->GetChild(1)->Operation();
	
	delete pComposite;
	system("pause");
}