组合模式

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

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

class Dir :public IFile
{
public:
	Dir(string name)
	{
		m_name = name;
		m_list = new list < IFile* > ;
		m_list->clear();
	}
	virtual void display()
	{
		cout << m_name << endl;
	}
	virtual bool add(IFile*root)
	{
		m_list->push_back(root);
		return 1;
	}
	virtual bool remove(IFile*root)
	{
		m_list->push_back(root);
		return 1;
	}
	virtual list<IFile*> *getChild()
	{
		return m_list;
	}
private:
	string m_name;
	list<IFile*> *m_list;
};

class File :public IFile
{
public:
	File(string name)
	{
		m_name = name;
	}
	virtual void display()
	{
		cout << m_name << endl;
	}
	virtual bool add(IFile*)
	{
		return 0;
	}
	virtual bool remove(IFile*)
	{
		return 0;
	}
	virtual list<IFile*> *getChild()
	{
		return NULL;
	}
private:
	string m_name;

};

void showTree(IFile*root, int lever)
{
	root->display();

	int i = 0;

	if (root->getChild() != NULL)
	{
		list<IFile*>*mylist = root->getChild();

		for (list<IFile*>::iterator it = mylist->begin(); it != mylist->end(); it++)
		{
			if ((*it)->getChild() == NULL)
			{
				for (i = 0; i <=lever; i++)
				{
					cout << "\t";
				}
				(*it)->display();
			}
			else
			{
				for (i = 0; i <= lever; i++)
				{
					cout << "\t";
				}
				showTree(*it, lever+1);
			}
		}
	}
	
}

void main()
{
	IFile *root = NULL;
	root = new Dir("C");

	Dir *dir1 = new Dir("Dir1");
	File *file1 = new File("file1");

	root->add(dir1);
	root->add(file1);
	showTree(root,0);


	Dir *dir2 = new Dir("Dir2");
	File *file2 = new File("file2");

	dir1->add(dir2);
	dir1->add(file2);
	showTree(root, 0);
}

运行结果:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值