读书人

复建:Replace Conditional with Poly

发布时间: 2012-11-20 09:55:43 作者: rapoo

重构: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.

当有条件句,它根据对象类型来选择不同的行为,这时就可以将条件句的每一个分支搬移到子类的覆盖方法中来实现。

?


复建:Replace Conditional with Polymorphism

假设这是原始代码:

?

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();    }
?

?

?

?

?

读书人网 >软件架构设计

热点推荐