重构:Replace Conditional with Polymorphism
You have a conditional that chooses different behavior depending on the type of an object.
Move each leg of the conditional to an overriding method in a subclass. Make the original method
abstract.
当有条件句,它根据对象类型来选择不同的行为,这时就可以将条件句的每一个分支搬移到子类的覆盖方法中来实现。
假设这是原始代码:
class Employee...
int payAmount() {
switch (getType()) {
case EmployeeType.ENGINEER:
return _monthlySalary;
case EmployeeType.SALESMAN:
return _monthlySalary + _commission;
case EmployeeType.MANAGER:
return _monthlySalary + _bonus;
default:
throw new 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;
}
... and other subclasses
After using Replace Conditional with Polymorphism:
// client
class Employee...
int payAmount() {
return _type.payAmount(this);
}
// interface
class EmployeeType...
abstract int payAmount(Employee emp);
// some concrete classes
class Engineer...
int payAmount(Employee emp) {
return emp.getMonthlySalary();
}
class Salesman...
int payAmount(Employee emp) {
return emp.getMonthlySalary() + emp.getCommission();
}
class Manager...
int payAmount(Employee emp) {
return emp.getMonthlySalary() + emp.getBonus();
}