switch

  1. //辅助代码
  2. public enum EmployeeType{
  3. COMMISIONED,
  4. HOURLY,
  5. SALARIED
  6. }
  7. public class Employee{
  8. public EmployeeType type;
  9. }
  10. public class Money{
  11. float val=0f;
  12. }
  13. public Money calculateCommissionedPay(e){
  14. return new Money();
  15. }
  16. public Money calculateHourlyPay(e){
  17. return new Money();
  18. }
  19. public Money calculateSalariedPay(e){
  20. return new Money();
  21. }
  22. //主函数:
  23. public Money calculatePay(Employee e){
  24. switch(e.type){
  25. case COMMISIONED:
  26. return calculateCommissionedPay(e);
  27. case HOURLY:
  28. return calculateHourlyPay(e);
  29. case SALARIED:
  30. return calculateSalariedPay(e);
  31. default:
  32. break;
  33. }
  34. }

上述代码的问题:

  • 出现新的员工类型时,必须进行修改,代码会变长。
  • 到处都可能有类似的结构,通过判断员工的类型来调用不同的函数。例如下面的代码。
    1. bool isPayDay(Employee e,Data date){}
    2. void deliverPay(Employee e,Money pay){}

    工厂模式

    抽象类

接口

抛出异常

  1. public abstract class Employee{
  2. public abstract bool isPayDay();
  3. public abstract Money calculatePay();
  4. public abstract void deliverPay();
  5. }
  6. public class CommissionedEmployee:Employee{
  7. public bool isPayDay();
  8. public Money calculatePay();
  9. public void deliverPay();
  10. }
  11. public class HourlyEmployee:Employee{
  12. public bool isPayDay();
  13. public Money calculatePay();
  14. public void deliverPay();
  15. }
  16. public class SalariedEmployee:Employee{
  17. public bool isPayDay();
  18. public Money calculatePay();
  19. public void deliverPay();
  20. }
  21. ////////////////////////////////////////////////////
  22. public interface EmployeeFactory{
  23. public Employee makeEmployee(EmployeeRecord r);
  24. }
  25. public class EmployeeFactorImpl:EmployeeFactory{
  26. public Employee makeEmployee(EmployeeRecord r){
  27. switch(r.type){
  28. case COMMISIONED:
  29. return new CommissionedEmployee(r);
  30. case HOURLY:
  31. return new HourlyEmployee(r);
  32. case SALARIED:
  33. return new SalariedEmployee(r);
  34. default:
  35. break;
  36. }
  37. }
  38. }