首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

复建:Replace Conditional with Polymorphism

2012-11-20 
重构:Replace Conditional with PolymorphismYou have a conditional that chooses different behavior de

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

?

?

?

?

热点排行