1、背景:JAVA代码中很经常出现if-else switch-case语句,为了根据对象不同而选择不同的表达式
2、
说明:针对鸟这个类提炼出子类Brid类,每个分支放进一个子类内的覆写函数中,然后将超类BridType函数声明为抽象函数
class Brid{
private int baseSpeed;
private int loadFactor;
private int numberOfCoconuts;
private BridType _type;
int getSpeed(){
return _type. getSpeed(this)
}
}
class BridType{
abstract int getSpeed(Brid brid);
}
class European extends BridType{
int getSpeed(Brid brid){
return brid.getBaseSpeed();
}
}
3、将表达式提炼到一个独立的函数,将分支提取到子类,将超类函数声明为抽象函数: