复杂的条件逻辑是编程中最难理解的东西之一,给条件逻辑添加结构

可以将条件逻辑拆分到不同的场景(或者叫高阶用例),从而拆分条件逻辑。使用类和多态能把逻辑的拆分表述得更清楚,多态是改善复杂条件逻辑的有力工具。

有两种常见场景,

一种是,好几个函数都有基于类型的switch语句,每个类型处理各自的条件逻辑。把switch中每个分支逻辑创建一个类,用多态来承载各个类型特有的行为。 

另一种是:有一个基础逻辑,在其上又有一些变体。基础逻辑放进基类,基础逻辑可能是最常用的,也可能是最简单的。变体放进子类,强调与基类基础逻辑的差异。

1,动机

例子,朋友有一群鸟,他想知道鸟飞得多快,以及鸟的羽毛是什么样的。

//朋友有一群鸟,他想知道鸟飞得有多快,以及它们的羽毛是什么样的。

//飞的多快
function speeds(birds) {
    return new Map(birds.map(b => [b.name, airSpeedVelocity(b)]));
}
//羽毛
function plumages(birds) {
    return new Map(birds.map(b => [b.name, plumage(b)]))
}


function plumage(bird){
    switch(bird.type){
        case 'EuropeanSwallow':
            return "average";
        case 'AfricanSwallow':
            return (bird.numberOfCoconuts>2)?"tired":"average";
        case 'NorwegianBlueParrot':
            return (bird.voltage>100)?'scorched':'beautiful';
        default:
            return 'unknow';
    }
}

function airSpeedVelocity(bird){
    switch(bird.type){
        case 'EuropeanSwallow':
            return 35;
        case 'AfricanSwallow':
            return 40-2*bird.numberOfCoconuts;
        case 'NorwegianBlueParrot':
            return (bird.isNailed)?0:10+bird.voltage/10;
        default:
            return null;
    }
}
View Code

相关文章:

  • 2022-12-23
  • 2021-08-28
  • 2021-12-26
  • 2021-07-07
  • 2022-12-23
  • 2021-07-22
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-08-31
  • 2022-01-13
  • 2021-10-15
  • 2021-05-31
  • 2022-12-23
相关资源
相似解决方案