switch
//辅助代码
public enum EmployeeType{
COMMISIONED,
HOURLY,
SALARIED
}
public class Employee{
public EmployeeType type;
}
public class Money{
float val=0f;
}
public Money calculateCommissionedPay(e){
return new Money();
}
public Money calculateHourlyPay(e){
return new Money();
}
public Money calculateSalariedPay(e){
return new Money();
}
//主函数:
public Money calculatePay(Employee e){
switch(e.type){
case COMMISIONED:
return calculateCommissionedPay(e);
case HOURLY:
return calculateHourlyPay(e);
case SALARIED:
return calculateSalariedPay(e);
default:
break;
}
}
上述代码的问题:
- 出现新的员工类型时,必须进行修改,代码会变长。
- 到处都可能有类似的结构,通过判断员工的类型来调用不同的函数。例如下面的代码。
bool isPayDay(Employee e,Data date){}
void deliverPay(Employee e,Money pay){}
工厂模式
抽象类
接口
抛出异常
public abstract class Employee{
public abstract bool isPayDay();
public abstract Money calculatePay();
public abstract void deliverPay();
}
public class CommissionedEmployee:Employee{
public bool isPayDay();
public Money calculatePay();
public void deliverPay();
}
public class HourlyEmployee:Employee{
public bool isPayDay();
public Money calculatePay();
public void deliverPay();
}
public class SalariedEmployee:Employee{
public bool isPayDay();
public Money calculatePay();
public void deliverPay();
}
////////////////////////////////////////////////////
public interface EmployeeFactory{
public Employee makeEmployee(EmployeeRecord r);
}
public class EmployeeFactorImpl:EmployeeFactory{
public Employee makeEmployee(EmployeeRecord r){
switch(r.type){
case COMMISIONED:
return new CommissionedEmployee(r);
case HOURLY:
return new HourlyEmployee(r);
case SALARIED:
return new SalariedEmployee(r);
default:
break;
}
}
}