C#设计模式编程之抽象工厂模式新解(2)

来源:互联网 发布:js中offset函数 编辑:程序博客网 时间:2024/04/28 01:58
抽象工厂之新解

   虚拟案例

  中国企业需要一项简单的财务计算:每月月底,财务人员要计算员工的工资。

  员工的工资 = (基本工资 + 奖金 - 个人所得税)。这是一个放之四海皆准的运算法则。

  为了简化系统,我们假设员工基本工资总是4000美金。

  中国企业奖金和个人所得税的计算规则是:

  奖金 = 基本工资(4000) * 10%

  个人所得税 = (基本工资 + 奖金) * 40%

  我们现在要为此构建一个软件系统(代号叫Softo),满足中国企业的需求。

   案例分析

  奖金(Bonus)、个人所得税(Tax)的计算是Softo系统的业务规则(Service)。

  工资的计算(Calculator)则调用业务规则(Service)来计算员工的实际工资。

  工资的计算作为业务规则的前端(或者客户端Client)将提供给最终使用该系统的用户(财务人员)使用。

   针对中国企业为系统建模

  根据上面的分析,为Softo系统建模如下:


  则业务规则Service类的代码如下:

1using System;
2
3namespace ChineseSalary
4{
5 /**//// <summary>
6 /// 公用的常量
7 /// </summary>
8 public class Constant
9 {
10 public static double BASE_SALARY = 4000;
11 }
12}
1using System;
2
3namespace ChineseSalary
4{
5 /**//// <summary>
6 /// 计算中国个人奖金
7 /// </summary>
8 public class ChineseBonus
9 {
10 public double Calculate()
11 {
12 return Constant.BASE_SALARY * 0.1;
13 }
14 }
15}
16

  客户端的调用代码:

1using System;
2
3namespace ChineseSalary
4{
5 /**//// <summary>
6 /// 计算中国个人所得税
7 /// </summary>
8 public class ChineseTax
9 {
10 public double Calculate()
11 {
12 return (Constant.BASE_SALARY + (Constant.BASE_SALARY * 0.1)) * 0.4;
13 }
14 }
15}
16

  运行程序,输入的结果如下:

  Chinese Salary is:2640

   针对美国企业为系统建模

  为了拓展国际市场,我们要把该系统移植给美国公司使用。 美国企业的工资计算同样是: 员工的工资 = 基本工资 + 奖金 - 个人所得税。

  但是他们的奖金和个人所得税的计算规则不同于中国企业:

  美国企业奖金和个人所得税的计算规则是:

  奖金 = 基本工资 * 15 %

  个人所得税 = (基本工资 * 5% + 奖金 * 25%)

  根据前面为中国企业建模经验,我们仅仅将ChineseTax、ChineseBonus修改为AmericanTax、AmericanBonus。 修改后的模型如下:


  则业务规则Service类的代码如下:

1using System;
2
3namespace AmericanSalary
4{
5 /**//// <summary>
6 /// 公用的常量
7 /// </summary>
8 public class Constant
9 {
10 public static double BASE_SALARY = 4000;
11 }
12}
13


1using System;
2
3namespace AmericanSalary
4{
5 /**//// <summary>
6 /// 计算美国个人奖金
7 /// </summary>
8 public class AmericanBonus
9 {
10 public double Calculate()
11 {
12 return Constant.BASE_SALARY * 0.1;
13 }
14 }
15}
16

1using System;
2
3namespace AmericanSalary
4{
5 /**//// <summary>
6 /// 计算美国个人所得税
7 /// </summary>
8 public class AmericanTax
9 {
10 public double Calculate()
11 {
12 return (Constant.BASE_SALARY + (Constant.BASE_SALARY * 0.1)) * 0.4;
13 }
14 }
15}
16

  客户端的调用代码:

1
2using System;
3
4namespace AmericanSalary
5{
6 /**//// <summary>
7 /// 客户端程序调用
8 /// </summary>
9 public class Calculator
10 {
11 public static void Main(string[] args)
12 {
13 AmericanBonus bonus = new AmericanBonus();
14 double bonusValue = bonus.Calculate();
15
16 AmericanTax tax = new AmericanTax();
17 double taxValue = tax.Calculate();
18
19 double salary = 4000 + bonusValue - taxValue;
20
21 Console.WriteLine("American Salary is:" + salary);
22 Console.ReadLine();
23 }
24 }
25}
26

  运行程序,输入的结果如下:

  American Salary is:2640

原创粉丝点击