23种设计模式C++实例之组合模式

  • 组合模式:将对象组合成树形结构来表示“部分-整体”的层次关系,并把整体当作一个单一对象,提供统一的接口。
  • 主要角色:
    • 组件接口
    • 叶子节点(单一对象)
    • 复合节点(符合对象)
    • 客户端
#include <iostream>
#include <list>

/*
 * 组合模式
 * 让单个对象和组合对象具有一致的接口
 * */

using namespace std;

class IFile {
	public:
		virtual ~IFile() {}
		virtual void display() = 0;
		virtual int add(IFile* iFile) = 0;
		virtual int remove(IFile* iFile) = 0;
		virtual list<IFile*>* getChild() = 0;
};

class File: public IFile {
	public:
		File(string name) {
			m_name = name;
		}
		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:
		string m_name;
};

class Folder: public IFile {
	public:
		Folder(string name) {
			m_name = name;
			m_list = new list<IFile*>;
			m_list->clear();
		}
		virtual ~Folder() {
			if (m_list != NULL) {
				delete m_list;
				m_list = NULL;
			}
		}
		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:
		string m_name;
		list<IFile*>* m_list;
};

// 递归显示树
void showTree(IFile* root, int level) {
	if (root == NULL) {
		return;
	}

	for(int i = 0; i < level; ++i) {
		cout << "\t";
	}

	// 1 显示根节点
	root->display();

	list<IFile*>* mylist = root->getChild();

	// 2 若子节点为文件,直接显示文件名
	if (mylist == NULL) {
		return;	
	} else {
	// 3 若子节点为文件夹,则递归调用
		for(list<IFile *>::iterator it = mylist->begin(); it != mylist->end(); ++it) {
			if ((*it)->getChild() == NULL) {
				for(int i = 0; i < level + 1; ++i) {
					cout << "\t";
				}
				(*it)->display();	
			} else {
				showTree(*it, level + 1);
			}
		}
	
	}
}

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

	File* file1 = new File("file1.txt");
	root->add(file1);

	Folder* folder1 = new Folder("folder1");
	File* file2 = new File("file2.txt");
	folder1->add(file2);
	root->add(folder1);

	showTree(root, 0);

	delete file1;
	delete folder1;
	delete root;

	return 0;
}

设计原则

创建模式(5种)

结构模式(7种)

行为模式(11种)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值