定义:撰写物体进入树形结构以表示“整体的一部分”阶层。组合模式使用户能够使用一个单一的对象和对象的均匀的组合。
组成:
以一个文件结构为例。
每个文件或者文件夹都能够看作一个节点。而对于文件夹节点又有加入删除子节点的操作。
首先定义一个抽象基类节点。
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;
}总体与部分须要被一致对待时。
版权声明:本文博客原创文章,博客,未经同意,不得转载。
原文:http://www.cnblogs.com/gcczhongduan/p/4649576.html