四.案例分析(Example

1、场景

假设公司组织结构为:
--总结理
----技术部门经理
------开发人员A
------开发人员B
----销售部门经理
总经理直接领导技术部经理和销售部经理,技术部经理直接领导开发人员A和开发人员B。销售部经理暂时没有直接下属员工,随着公司规模增大,销售部门会新增销售员工。计算组织结构的总工资状况。
如下图所示

Net设计模式实例之组合模式(Composite Pattern)(2)

IComponent接口:此接口包括了ComponentComposite的所有属性,公司每个角色都有职称Title和工资待遇SalaryAdd方法把员工加入到组织团队中。
Component叶子节点:叶节点没有子节点,Add方法实现没有任何意义。
Composite组合类:此类有一个员工集合_listEmployees,Add方法向此集合中添加员工信息。
GetCost方法获得组织结构中的工资待遇总和

2、代码

1、接口IComponent
  1. public interface IComponent   
  2.     {   
  3.         string Title { getset; }   
  4.         decimal Salary { getset; }   
  5.         void Add(IComponent c);   
  6.         void GetCost(ref decimal salary);   
  7.     }   
8.    
 
2、叶节点Component 
  1. public class Component : IComponent   
  2.     {   
  3.         public string Title { getset; }   
  4.         public decimal Salary { getset; }   
  5.   
  6.         public Component(string Title, decimal Salary)   
  7.         {   
  8.             this.Title = Title;   
  9.             this.Salary = Salary;   
  10.         }   
  11.   
  12.         public void Add(IComponent c)   
  13.         {   
  14.             Console.WriteLine("Cannot add to the leaf!");   
  15.         }   
  16.   
  17.         public void GetCost(ref decimal salary)   
  18.         {   
  19.             salary += Salary;   
  20.         }   
  21.     }   
22.    









本文转自 灵动生活 51CTO博客,原文链接:http://blog.51cto.com/smartlife/267505,如需转载请自行联系原作者

相关文章: