重构: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.
当有条件句,它根据对象类型来选择不同的行为,这时就可以将条件句的每一个分支搬移到子类的覆盖方法中来实现。
?

假设这是原始代码:
?
After using Replace Conditional with Polymorphism:
?
// clientclass Employee... int payAmount() { return _type.payAmount(this); }// interfaceclass EmployeeType... abstract int payAmount(Employee emp);// some concrete classesclass 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(); }??
?
?
?