C#复合模式(Composite Pattern) C#复合模式(Composite Pattern)实例教程
人气:0想了解C#复合模式(Composite Pattern)实例教程的相关内容吗,在本文为您仔细讲解C#复合模式(Composite Pattern)的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:C#,复合,模式,下面大家一起来学习吧。
本文以一个简单实例的形式讲述了C#复合模式。分享给大家供大家参考。具体实现方法如下:
一般在显示树形结构时,复合模式有很好的体现。本文实例显示如下部门结构:
如上图所示,有的节点包含子节点,有的节点不包含子节点。不管是什么节点,每个节点就代表一个部门。
首先设计一个关于部门的抽象基类。
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(); } }
程序运行结果如下图所示:
希望本文所述对大家C#程序设计的学习有所帮助。
加载全部内容