首页 > 代码库 > 用最简单的例子理解复合模式(Composite Pattern)
用最简单的例子理解复合模式(Composite Pattern)
在显示树形结构时,复合模式有很好的体现。本篇显示如下部门结构:
以上,有的节点包含子节点,有的节点部包含子节点。不管是什么节点,每个节点就代表一个部门。
首先设计一个关于部门的抽象基类。
public abstract class DepartmentComponent{public string Name { private set; get; }public DepartmentComponent(string name){this.Name = name;
}public virtual void PrintSupervisorOf(int spacing){for (int counter = 0; counter < spacing; counter++){Console.Write(" ");
}Console.WriteLine(Name);}}
以上,通过构造函数给属性赋值,通过PrintSupervisorOf(int spacing)方法打印出节点的名称。
接下来设计包含子节点的节点。该类维护着DepartmentComponent类型的集合,提供方法向这个集合中添加节点或从集合中删除节点。
public class DepartmentComposite : DepartmentComponent{private IList<DepartmentComponent> employees;
public DepartmentComposite(string name) : base(name){employees = new List<DepartmentComponent>();
}public void AddDepartment(DepartmentComponent e){employees.Add(e);}public void RemoveDepartment(DepartmentComponent e){employees.Remove(e);}public override void PrintSupervisorOf(int spacing){base.PrintSupervisorOf(spacing);
foreach (DepartmentComponent e in employees){e.PrintSupervisorOf(spacing + 1);}}}
以上 PrintSupervisorOf(int spacing)方法重写了抽象基类的方法,不仅把本节点的名称打印出来,还使用递归把所有子节点的名称显示出来。
最后设计部包含子节点的节点。
public class Department : DepartmentComponent{public Department(string name) : base(name){}public override void PrintSupervisorOf(int spacing){base.PrintSupervisorOf(spacing);
}}
客户端部分。
class Program
{static void Main(string[] args){DepartmentComposite salesDepartment1 = new DepartmentComposite("销售部1");Department zhangsan = new Department("张三");Department lisi = new Department("李四");DepartmentComposite salesDepartment2 = new DepartmentComposite("销售部2");DepartmentComposite specialDepartment = new DepartmentComposite("销售部2特别行动组");Department wangwu = new Department("王五");Department zhaoliu = new Department("赵六");DepartmentComposite salesDepartment = new DepartmentComposite("销售部");salesDepartment.AddDepartment(salesDepartment1);salesDepartment.AddDepartment(salesDepartment2);salesDepartment1.AddDepartment(zhangsan);salesDepartment1.AddDepartment(lisi);salesDepartment2.AddDepartment(specialDepartment);specialDepartment.AddDepartment(wangwu);specialDepartment.AddDepartment(zhaoliu);salesDepartment.PrintSupervisorOf(0);Console.ReadKey();}}
用最简单的例子理解复合模式(Composite Pattern)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。