欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#复合模式(Composite Pattern)实例教程

程序员文章站 2023-12-16 16:46:28
本文以一个简单实例的形式讲述了c#复合模式。分享给大家供大家参考。具体实现方法如下: 一般在显示树形结构时,复合模式有很好的体现。本文实例显示如下部门结构: 如上图...

本文以一个简单实例的形式讲述了c#复合模式。分享给大家供大家参考。具体实现方法如下:

一般在显示树形结构时,复合模式有很好的体现。本文实例显示如下部门结构:

C#复合模式(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();
    }
}

程序运行结果如下图所示:

C#复合模式(Composite Pattern)实例教程

希望本文所述对大家c#程序设计的学习有所帮助。

上一篇:

下一篇: