编辑
2025-09-28
C#
00

目录

摘要
正文
组合模式的关键角色
组合模式的优点
组合模式的缺点
示例:文件系统的表示

摘要

组合模式是一种结构型设计模式,它允许你将对象组合成树形结构来表现整体/部分的层次结构。组合模式使得客户端可以统一对待单个对象和组合对象。

正文

组合模式的关键角色

  • Component:这是组合中对象声明接口的抽象类,在适当的情况下,实现所有类共有接口的默认行为。它声明了一个接口用于访问和管理子部件。
  • Leaf:在组合中表示叶节点对象,叶节点没有子节点。
  • Composite:定义有子部件的那些部件的行为,存储子部件,并在Component接口中实现与子部件有关的操作。

组合模式的优点

  • 简化客户端代码,因为它可以一致地对待单个对象和组合对象。
  • 更容易增加新类型的组件,因为你不需要改变现有的代码。

组合模式的缺点

  • 设计上可能会更加复杂,因为你需要创建一个共同的接口和一个抽象类,这些类的层次结构可以变得非常深和复杂。
  • 在组合模式中,设计初期需要仔细考虑系统的结构,以支持未来的变化。

示例:文件系统的表示

让我们通过一个例子来理解组合模式,我们将创建一个简单的文件系统表示,其中每个目录可以包含其他目录或文件。

首先,我们定义组件接口:

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); }

image.png

组合模式在C#中的应用非常广泛,例如在UI组件中,一个窗口可以包含面板,面板又可以包含按钮、文本框等控件,每个控件都可以是一个叶节点或者一个包含其他控件的复合节点。这种结构使得我们可以统一处理单个控件和组合控件,从而简化了UI的管理和操作。

本文作者:技术老小子

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!