设计模式组合模式

定义:撰写物体进入树形结构以表示“整体的一部分”阶层。组合模式使用户能够使用一个单一的对象和对象的均匀的组合。

组成:
1.Component 是组合中的对象声明接口,在适当的情况下,实现全部类共同拥有接口的默认行为。声明一个接口用于訪问和管理Component子部件。
2.Leaf 在组合中表示叶子结点对象。叶子结点没有子结点。
3.Composite 定义有枝节点行为,用来存储子部件,在Component接口中实现与子部件有关操作,如添加(add)和删除(remove)等。



以一个文件结构为例。

每个文件或者文件夹都能够看作一个节点。而对于文件夹节点又有加入删除子节点的操作。


首先定义一个抽象基类节点。

class Node
{
public:
	virtual void Add(Node* tmp)=0;
	virtual void Remove()=0;
	virtual void Display(string str)=0;
};

对于文件节点,没有加入删除操作。

class File : public Node
{
private:
	string Name;
	void Add(Node* c){}
	void Remove(){}
public:
	File(string name) { Name = name; }
	void Display(string str)
	{
		string strtmp = str + Name;
		cout<<strtmp<<endl;
	}
};

对于目录,能够用一个链表来存储其子目录和文件

class DirFolder :public  Node
{
private:
	list<Node*> subfolder;
	string Name;
public:
	int length = 0;
	DirFolder(string name) { Name = name; }
	void Add(Node* tmp)
	{
		length = length + 1;
		subfolder.push_back(tmp);
	}
	void Remove()
	{
		if (length == 0) return;
		length = length - 1;
		subfolder.pop_back();
	}
	void Display(string str)
	{
		cout<<str<<Name<<endl;
		str = str + "---";
		for (Node* component:subfolder)
		{
			component->Display(str);
		}
	}
};

測试:

int main()
{
	DirFolder root("root");
	//加入文件
	File* file1=new File("file1");
	root.Add(file1);
	//加入子目录
	File* file2=new File("file2");
	root.Add(file2);


	//加入文件
	DirFolder* subdir=new DirFolder("subdir");
	File* file3=new File("file3");
	subdir->Add(file3);
	File* file4=new File("file4");
	subdir->Add(file4);


	//删除子目录
	root.Add(subdir);
	root.Display("");
	root.Remove();
	root.Display("");
	return 0;
}




适用:
表示对象的部分-总体层次结构

总体与部分须要被一致对待时。



版权声明:本文博客原创文章,博客,未经同意,不得转载。

原文地址:https://www.cnblogs.com/gcczhongduan/p/4649576.html