原因:在编程中,使用if-else语句是一种常见的控制结构,用于根据条件执行不同的代码块。虽然if-else语句非常有用,但在某些情况下可能会导致代码变得冗长或效率较低。
const result = condition && action();
const result = condition ? action1() : action2();
const actions = {
condition1: () => {
// 执行操作1
},
condition2: () => {
// 执行操作2
},
default: () => {
// 执行默认操作
},
};
actions[condition] ? actions[condition]() : actions.default();
const actions = [
{
condition: condition1,
action: () => {
// 执行操作1
},
},
{
condition: condition2,
action: () => {
// 执行操作2
},
},
{
condition: () => true,
action: () => {
// 执行默认操作
},
},
];
actions.find((item) => item.condition())?.action();
function doAction1() {
// 执行操作1
}
function doAction2() {
// 执行操作2
}
function defaultAction() {
// 执行默认操作
}
if (condition1) {
doAction1();
} else if (condition2) {
doAction2();
} else {
defaultAction();
}
switch (condition) {
case condition1:
// 执行操作1
break;
case condition2:
// 执行操作2
break;
default:
// 执行默认操作
}
const result = condition
? action1()
: condition2
? action2()
: defaultAction();
const FLAG_A = 0b001;
const FLAG_B = 0b010;
if (condition & FLAG_A) {
// 执行操作A
}
if (condition & FLAG_B) {
// 执行操作B
}
class Strategy {
constructor(condition, action) {
this.condition = condition;
this.action = action;
}
canHandle() {
return this.condition();
}
handle() {
this.action();
}
}
const strategies = [
new Strategy(condition1, () => {
// 执行操作1
}),
new Strategy(condition2, () => {
// 执行操作2
}),
new Strategy(() => true, () => {
// 执行默认操作
}),
];
const strategy = strategies.find((strategy) => strategy.canHandle());
strategy.handle();
状态模式
class State {
constructor(condition, action) {
this.condition = condition;
this.action = action;
}
canEnter() {
return this.condition();
}
enter() {
this.action();
}
}
class StateMachine {
constructor() {
this.states = [
new State(condition1, () => {
// 执行操作1
}),
new State(condition2, () => {
// 执行操作2
}),
new State(() => true, () => {
// 执行默认操作
}),
];
}