简化条件表达式之以多态取代条件表达式(Replace Conditional with Polymorphism)

你手上一个条件表达式,它根据对象类型的不同而选择不同的行为。将这个条件表达式的每个分支放进一个子类的覆写函数中,然后将原始函数声明为抽象函数。

动机:多态的最根本的好处是:如果你需要根据对象的不同类型而采取不同的行为,多态使你不必编写某些的条件表达式。

       正因为有了多态,所以你会发现:“类型吗的switch语句”以及 ”基于类型名称的if-then-else语句“在面向对象程序中很少出现。

       多态能够给你带来很多好处。如果同一组条件表达式在程序的许多地点出现,那么使用多态的收益是最大的。使用条件表达式时,如果你想添加一种新类型,就必须查找并更新所有条件表达式。但如果使用多态,只需建立一个新的子类,并在其中提供适当的函数就行了。类的用户不需要了解这个子类,这就大大降低了系统各部分之间的依赖,使系统升级更加容易。

class Engineer extends EmployeeType{
    int getTypeCode(){
        return Employee.ENGINEER;
    }
}
class Manager extends EmployeeType{
    int getTypeCode(){
        return Employee.MANAGER;
    }
}
class Salesman extends EmployeeType{
    int getTypeCode(){
        return Employee.SALEMAN;
    }
}
class Employee...
private employeeType _type;
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();
    }
}
int getType(){
    return _type.getTypeCode();
}
void setType(int arg){
    _type = EmployeeType.newType(arg);
}
class employeeType...
static EmployeeType newType(int code){
    switch(code){
        case ENGINEER:
            return new Engineer();
        case SALESMAN:
            return new Salesman();
        case MANAGER:
            return new Manager();
        default:
            throw new IllegalArgumentException();
    }
}
static final int ENGINEER = 0;
static final int SALESMAN = 1;
static final int MANAGER = 2;

使用多态后

class Engineer extends EmployeeType{
    int getTypeCode(){
        return Employee.ENGINEER;
    }
}
class Manager extends EmployeeType{
    int getTypeCode(){
        return Employee.MANAGER;
    }
}
class Salesman extends EmployeeType{
    int getTypeCode(){
        return Employee.SALEMAN;
    }
}
class Employee...
private employeeType _type;
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();
    }
}
int getType(){
    return _type.getTypeCode();
}
void setType(int arg){
    _type = EmployeeType.newType(arg);
}
class employeeType...
static EmployeeType newType(int code){
    switch(code){
        case ENGINEER:
            return new Engineer();
        case SALESMAN:
            return new Salesman();
        case MANAGER:
            return new Manager();
        default:
            throw new IllegalArgumentException();
    }
}
static final int ENGINEER = 0;
static final int SALESMAN = 1;
static final int MANAGER = 2;
扫描二维码关注公众号,回复: 8069336 查看本文章

猜你喜欢

转载自www.cnblogs.com/newbee0101/p/11982109.html
今日推荐