C#复合模式(Composite Pattern)实例教程
程序员文章站
2023-12-20 09:16:46
本文以一个简单实例的形式讲述了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#程序设计的学习有所帮助。
推荐阅读
-
C#命令模式(Command Pattern)实例教程
-
C#复合模式(Composite Pattern)实例教程
-
C#模板方法模式(Template Method Pattern)实例教程
-
C#策略模式(Strategy Pattern)实例教程
-
C#对象为Null模式(Null Object Pattern)实例教程
-
C#单例模式(Singleton Pattern)实例教程
-
C#装饰器模式(Decorator Pattern)实例教程
-
C#模板方法模式(Template Method Pattern)实例教程
-
C#观察者模式(Observer Pattern)实例教程
-
C#迭代器模式(Iterator Pattern)实例教程