【C#设计模式(9)——组合模式(Component Pattern)】

时间:2024-11-15 10:26:17
//目录抽象类 public abstract class Directory { protected string _name; public Directory(string name) { _name = name; } public abstract void Show(); } //子目录 public class SubDirectory : Directory { public SubDirectory(string name) : base(name) { } public override void Show() { Console.WriteLine($"sub directory show : {_name}"); } } //父目录 public class ParentDirectory : Directory { private List<Directory> children; public ParentDirectory(string name) : base(name) { children = new List<Directory>(); } public void Add(Directory catalogue) { children.Add(catalogue); } public void Remove(Directory catalogue) { children.Remove(catalogue); } public override void Show() { Console.WriteLine($"Parent directory show : {_name}"); foreach (var item in children) { item.Show(); } } } /* * 结构型模式:Structural Pattern * 组合模式: Component Pattern * 组合模式是将对象组合成树形结构以表示“整体-部分”的层次结构使客户终端代码更加简洁和灵活。 */ internal class Program { static void Main(string[] args) { //创建父目录 ParentDirectory rootDirectory =new ParentDirectory("root"); ParentDirectory parentDirectory1 = new ParentDirectory("parent1"); ParentDirectory parentDirectory2 = new ParentDirectory("parent2"); //创建子目录 SubDirectory subDirectory1 = new SubDirectory("sub1"); SubDirectory subDirectory2 = new SubDirectory("sub2"); SubDirectory subDirectory3 = new SubDirectory("sub3"); //添加目录到... rootDirectory.Add(parentDirectory1); rootDirectory.Add(parentDirectory2); parentDirectory1.Add(subDirectory1); parentDirectory2.Add(subDirectory2); parentDirectory2.Add(subDirectory3); //查看目录 rootDirectory.Show(); Console.ReadLine(); } }