组合模式&&外观模式

组合模式

#include
class IFile {
public:
	virtual void display() = 0;
	virtual int add(IFile *ifile) = 0;//添加一个文件
	virtual int remove(IFile *ifile) = 0;//移除一个文件
	virtual list* getchile() = 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* getchile() {
		return NULL;
	}//获得文件夹下所有文件
private:
	string m_name;
};
class Dir:public IFile {
public:
	Dir(string name)
	{
		m_name = name;
		m_list = new list;
		m_list->clear();
	}
	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* getchile() {
		return m_list;
	}//获得文件夹下所有文件
private:
	string m_name;
	list *m_list;
};
void showTree(IFile *root)
{
	//递归显示树
	//1.显示根节点
	//2.若 根节点有孩子
		//(孩子是文件直接返回名字)
		//孩子是目录,接着shoeTree(子目录)
	if (root == NULL)
	{
		return;
	}
	root->display();
	list *m_list= root->getchile();
	if (m_list != NULL)
	{
		for (list ::iterator it = m_list->begin(); it != m_list->end(); it++)
		{
			if((*it)->getchile()==NULL)
			{
				(*it)->display();
			}
			else {
				showTree(*it);
			}
		}
	}
}
void main() {

	Dir *root = new Dir("C");
	Dir *dir1 = new Dir("child1");
	File *aaafile = new File("aaa.txt");

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

	Dir *dir11 = new Dir("child11");
	File *aaafile11 = new File("aaa11.txt");
	
	
	list *m_list = root->getchile();
	for (list ::iterator it = m_list->begin(); it != m_list->end(); it++)
	{
		(*it)->display();
	}
	dir1->add(dir11);
	dir1->add(aaafile11);
	showTree(root);
	system("pause");
}

组合模式我理解的是定义了一个共用的接口,将对象组合成树形结构以表示“部分整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。

外观模式

  

#include 
using namespace std;

class SubSystemA
{
public:
	void doThing()
	{
		cout << "SubSystemA run" << endl;
	}
};

class SubSystemB
{
public:
	void doThing()
	{
		cout << "SubSystemB run" << endl;
	}
};

class SubSystemC
{
public:
	void doThing()
	{
		cout << "SubSystemC run" << endl;
	}
};


class Facade
{
public:
	Facade()
	{
		sysA = new SubSystemA;
		sysB = new SubSystemB;
		sysC = new SubSystemC;
	}
	~Facade()
	{
		delete sysA;
		delete sysB;
		delete sysC;
	}
public:
	void doThing()
	{
		sysA->doThing();
		sysB->doThing();
		sysC->doThing();
	}
protected:
private:
	SubSystemA *sysA;
	SubSystemB *sysB;
	SubSystemC *sysC;
};

void main1801()
{
	SubSystemA *sysA = new SubSystemA;
	SubSystemB *sysB = new SubSystemB;
	SubSystemC *sysC = new SubSystemC;

	sysA->doThing();
	sysB->doThing();
	sysC->doThing();
	delete sysA;
	delete sysB;
	delete sysC;
	
	return ;
}

void main1802()
{
	Facade *f = new Facade;
	f->doThing();
	delete f;

}

void main()
{
	//main1801();
	main1802();
	system("pause");
}

 

你可能感兴趣的:(C++)