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

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值