天天看點

C/C++設計模式(八) 組合模式

概念

組合模式(Composite模式),是構造型的設計模式之一。通過遞歸手段來構造樹形的對象結構,并可以通過一個對象來通路整個對象樹。

角色和職責

C/C++設計模式(八) 組合模式

Component (樹形結構的節點抽象)

為所有的對象定義統一的接口(公共屬性,行為等的定義)

提供管理子節點對象的接口方法

[可選]提供管理父節點對象的接口方法

Leaf(樹形結構的葉節點)

Component的實作子類

Composite(樹形結構的枝節點)

Component的實作子類

适用于:單個對象群組合對象的使用具有一緻性。将對象組合成樹形結構以表示“部分--整體”

案例

#include <iostream>
using namespace std;
#include "list"
#include "string"

//
class IFile
{
public:
	virtual void display() = 0;
	virtual int add(IFile *ifile) = 0;
	virtual int remove(IFile *ifile) = 0;
	virtual list<IFile *>* getChild() = 0;
protected:
private:
};

class File : public IFile
{
public:
	File(string name)
	{
		m_list = NULL;
		m_name = "";
		m_name = name;
	}
	~File()
	{
		if (m_list != NULL)
		{
			delete m_list;
		}
	}
	virtual void display()
	{
		cout << m_name << endl;
	}
	virtual int add(IFile *ifile)
	{
		return -1;
	}
	virtual int remove(IFile *ifile)
	{
		return -1;
	}
	virtual list<IFile *>* getChild() 
	{
		return NULL;
	}

private:
	list<IFile *> *	m_list;
	string		m_name;

};

class Folder : public IFile
{
public:
	Folder(string name)
	{
		m_name = name;
		m_list = new list<IFile *>;
	}
	~Folder()
	{
		if (m_list == NULL)
		{
			delete m_list;
		}
	}
	virtual void display()
	{
		cout << m_name << endl;
	}
	virtual int add(IFile *ifile)
	{
		m_list->push_back(ifile);
		return 0;
	}
	virtual int remove(IFile *ifile)
	{
		m_list->remove(ifile);
		return 0;
	}
	virtual list<IFile *>* getChild() 
	{
		return m_list;
	}

private:
	list<IFile *> *	m_list;
	string			m_name;

};

void showTree(IFile *ifile, int level)
{
	list<IFile *> *l = NULL;
	int i = 0;
	for (i=0; i<level; i++)
	{
		printf("\t");
	}
	ifile->display();

	l = ifile->getChild();
	if (l != NULL)
	{
		for (list<IFile *>::iterator it=l->begin(); it!=l->end(); it++)
		{
			if ( (*it)->getChild() == NULL)
			{
				for (i=0; i<=level; i++) //注意 <= 
				{
					printf("\t");
				}
				(*it)->display();
			}
			else
			{
				showTree((*it), level + 1);
			}

		}
	}
}

void main()
{
	Folder *root = new Folder("C:");

	Folder *dir1 = new Folder("111dir");
	File *txt1 = new File("aaa.txt");

	Folder *dir12 = new Folder("222dir");
	//dir12->display();
	File *txt12 = new File("222.txt");
	//txt12->display();

	
	root->display();
	root->add(dir1);
	root->add(txt1);

	dir1->add(dir12);
	dir1->add(txt12);

	/*
	list<IFile *> *l = dir1->getChild();
	for (list<IFile *>::iterator it=l->begin(); it!=l->end(); it++)
	{
		(*it)->display();
	}
	*/
	//開發一個遞歸函數 現在根結點下的所有子結點
	cout << "測試遞歸函數" << endl;

	showTree(root, 0);

	delete txt12;
	delete dir12;
	delete dir1;
	delete txt1;
	delete root;
	cout<<"hello..."<<endl;
	system("pause");
	return ;
}
           
C/C++設計模式(八) 組合模式

關注公衆号:《碼之有道》,一起聊遊戲全棧開發!

1、公衆号回複:【教程】擷取零基礎遊戲開發用戶端+服務端全套教程。

2、公衆号回複:【實戰】擷取企業級實戰項目。

3、公衆号回複:【資料】擷取大學四年整理的所有自學資料。

繼續閱讀