您的位置:首页 > 编程语言 > C#

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

2010-01-18 10:01 549 查看

四.案例分析(Example)

1、场景

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



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

2、代码

1、接口IComponent
public interface IComponent
{
string Title { get; set; }
decimal Salary { get; set; }
void Add(IComponent c);
void GetCost(ref decimal salary);
}

[align=left]8. [/align]
2、叶节点Component
public class Component : IComponent
{
public string Title { get; set; }
public decimal Salary { get; set; }

public Component(string Title, decimal Salary)
{
this.Title = Title;
this.Salary = Salary;
}

public void Add(IComponent c)
{
Console.WriteLine("Cannot add to the leaf!");
}

public void GetCost(ref decimal salary)
{
salary += Salary;
}
}

[align=left]22. [/align]
[align=left] [/align]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息