组合模式是一种结构型设计模式,它允许你将对象组合成树形结构来表现整体/部分的层次结构。组合模式使得客户端可以统一对待单个对象和组合对象。
让我们通过一个例子来理解组合模式,我们将创建一个简单的文件系统表示,其中每个目录可以包含其他目录或文件。
首先,我们定义组件接口:
C#// 组件接口
public abstract class FileSystemComponent
{
protected string name;
public FileSystemComponent(string name)
{
this.name = name;
}
public abstract void Add(FileSystemComponent component);
public abstract void Remove(FileSystemComponent component);
public abstract void Display(int depth);
}
接下来,我们实现叶节点,即文件:
C#// 叶节点
public class File : FileSystemComponent
{
public File(string name) : base(name) { }
// 叶节点没有子部件,所以Add和Remove方法可以提供默认实现
public override void Add(FileSystemComponent component)
{
throw new NotImplementedException("Cannot add to a file.");
}
public override void Remove(FileSystemComponent component)
{
throw new NotImplementedException("Cannot remove from a file.");
}
// 显示文件名称,带有深度缩进
public override void Display(int depth)
{
Console.WriteLine(new String('-', depth) + name);
}
}
然后,我们实现复合节点,即目录:
C#// 复合节点
public class Directory : FileSystemComponent
{
private List<FileSystemComponent> components = new List<FileSystemComponent>();
public Directory(string name) : base(name) { }
// 添加子部件
public override void Add(FileSystemComponent component)
{
components.Add(component);
}
// 移除子部件
public override void Remove(FileSystemComponent component)
{
components.Remove(component);
}
// 显示目录及其子部件,带有深度缩进
public override void Display(int depth)
{
Console.WriteLine(new String('-', depth) + name);
// 递归显示子部件
foreach (var component in components)
{
component.Display(depth + 2);
}
}
}
现在,我们可以构建一个文件系统的层次结构,并显示它:
C#static void Main(string[] args)
{
// 创建根目录
Directory rootDirectory = new Directory("Root");
// 创建文件
File file1 = new File("File1.txt");
File file2 = new File("File2.docx");
// 将文件添加到根目录
rootDirectory.Add(file1);
rootDirectory.Add(file2);
// 创建子目录
Directory subDirectory = new Directory("SubDirectory");
// 创建文件并添加到子目录
File file3 = new File("File3.pdf");
subDirectory.Add(file3);
// 将子目录添加到根目录
rootDirectory.Add(subDirectory);
// 显示文件系统结构
rootDirectory.Display(1);
}
组合模式在C#中的应用非常广泛,例如在UI组件中,一个窗口可以包含面板,面板又可以包含按钮、文本框等控件,每个控件都可以是一个叶节点或者一个包含其他控件的复合节点。这种结构使得我们可以统一处理单个控件和组合控件,从而简化了UI的管理和操作。
本文作者:技术老小子
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!