重构之多态消除条件分支
最近翻看之前写过一个项目,其中用到了大量的 switch-case 分支语句,大致的代码结构如下
代码演示
class A {
run() {
console.log(A.name, 'run1!');
}
}
class B {
run() {
console.log(B.name, 'run2!');
}
}
class C {
run() {
console.log(C.name, 'run3!');
}
}
function fun1(type) {
let temp;
switch (type) {
case 1:
temp = new A();
break;
case 2:
temp = new B();
break;
case 3:
temp = new C();
break;
default:
throw new Error('Unsupported types');
break;
}
temp.run();
}
fun1(1);