重构第九章
6.Replace Conditional with Polymorphism(以多态取代条件式)
你手上有个条件式,它根据对象型别的不同而选择不同的行为。将这个条件式的每个分支放进一个subclass内的覆写函数中,然后将原始函数声明为抽象函数。
Example:
class Enployee...
int payAmount() {
switch(getType()) {
case EmployeeType.ENGINEER:
return _monthlySalary;
case EmployeeType.SALESMAN:
return _monthlySalary + _commission;
case EmployeeType.MANAGER:
return _monthlySalary + bonus;
default:
throw now RuntimeException("Incorrect Employee");
}
}
int getType() {
return _type.getTypeCode();
}
private EmployeeType _type;
abstract class EmployeeType...
abstract int getTypeCode();
class Engineer extends EmployeeType...
int getTypeCode() {
return Employee.ENGINEER;
}
class SALESMAN extends EmployeeType...
int getTypeCode() {
return Employee.SALESMAN;
}
class MANAGER extends EmployeeType...
int getTypeCode() {
return Employee.MANAGER;
}
End:
class Engineer...
int payAmount(Employee emp) {
return emp.getMonthlySalary()
}
class Saleman...
int payAmount(Employee emp) {
return emp.getMonthlySalary() + emp.getCommission();
}
class Manager...
int payAmount(Employee tmp) {
return emp.getMonthlySalary() + emp.getBonus();
}
class EmployeeType...
abstract int payAmount(Employee tmp);
class Employee...
int payAmount() {
return _type.payAmount(this);
}
Conclusion:
多态最根本的好处就是:如果你需要根据对象的不同型别而采取不同的行为,多态使你不用编写明显的条件式。
如果你想添加一种新型别,就必须查找并更新所有条件式;Replace Conditional with Polymorphism(以多态取代条件式)使用多态可以建立一个新的subsclass,并在其中提供适当的函数。class用户不需要了解这个subclass,这就大大降低了系统各部分的相依程度。
注意
重构必须在有单元测试的情况下,保证之前的功能修改后不收影响。切记!!!
网友评论