设计模式 三

组合模式

#include 
#include 
#include 
using namespace std;


class IFile
{
public:
	virtual ~IFile() {}
	virtual void remove(IFile *) = 0;
	virtual void addFile(IFile *) = 0;
	virtual void show() = 0;
	virtual list *getChild() = 0;
	virtual string getName() = 0;
};

class File :public IFile
{
public:
	File(string name)
	{
		this->name = name;
	}
	string getName()
	{
		return name;
	}
	 void show()
	{
		cout << name << endl;
	}
	 void remove(IFile *)
	{
		return;
	}
	 void addFile(IFile *)
	{
		return;
	}
	 list *getChild()
	{
		return NULL;
	}
protected:
	string name;
	
	
};
class De :public IFile
{
public:
	De(string name)
	{
		this->name = name;
		_list = new list;
	}
	~De()
	{
		if (_list != NULL)
		{
			while (_list->empty())
			{
				delete *(_list->begin());
				_list->erase(_list->begin());
			}
			delete _list;
		}
	}
	string getName()
	{
		return name;
	}
	 void remove(IFile *file)
	{
		_list->remove(file);
	}
	 void addFile(IFile *file)
	{
		_list->push_back(file);
	}
	 void show()
	{
		cout << name << endl;
	}
	 list*getChild()
	{
		return _list;
	}
protected:
	string name;
	list*_list;

};
void func(IFile *pc1)
{
	IFile *pf1 = new File("大黄蜂.mp4");
	IFile *pf2 = new File("新喜剧之王.mp4");
	IFile *pf3 = new File("死侍.mp4");
	IFile *pf4 = new File("哈利波特1.mp4");
	IFile *pf5 = new File("哈利波特2.mp4");
	IFile *pf6 = new File("哈利波特3.mp4");
	IFile *pf7 = new File("面试宝典.pdf");
	IFile *pf8 = new File("剑指offer.pdf");
	IFile *pf9 = new File("仙剑奇侠传1.exe");
	IFile *pf10 = new File("仙剑奇侠传2.exe");
	IFile *pf11= new File("仙剑奇侠传3.exe");
	IFile *pf12= new File("魂斗罗.exe");
	IFile *pf13 = new File("超级玛丽.exe");
	
	
	
	IFile *pc2 = new De("电影");
	IFile *pc3 = new De("哈利波特");
	IFile *pc4 = new De("学习");
	IFile *pc5 = new De("游戏");
	IFile *pc6 = new De("仙剑奇侠传");

	pc1->addFile(pc2);
	pc1->addFile(pc4);
	pc1->addFile(pc5);

	pc2->addFile(pf1);
	pc2->addFile(pf2);
	pc2->addFile(pf3);
	pc2->addFile(pc3);

	pc3->addFile(pf4);
	pc3->addFile(pf5);
	pc3->addFile(pf6);

	pc4->addFile(pf7);
	pc4->addFile(pf8);

	pc5->addFile(pc6);
	pc5->addFile(pf12);
	pc5->addFile(pf13);

	pc6->addFile(pf9);
	pc6->addFile(pf10);
	pc6->addFile(pf11);
}
bool compare(IFile *left, IFile *right)
{
	return left->getName() < right->getName();
}
void show(IFile *pc1,int level)
{
	for (int i = 0; i < level; i++)
		cout << "    ";

	pc1->show();


	
	list*m_list = pc1->getChild();

	m_list->sort(compare);
	if (m_list != NULL)
	{
		list::iterator it = m_list->begin();

		while (it != m_list->end())
		{
			show((*it), level + 1);
			++it;
		}
	}
	
}
int main()
{
	
	IFile *pc1 = new De("D盘");
	func(pc1);

	show(pc1, 0);


	system("pause");
	return 0;


}

你可能感兴趣的:(设计模式 三)