策略模式代替传统的if else语句:可以增加可读性,维护性,复用性,降低复杂度,灵活
代码例子:
// 定义策略对象
const strategies = {
'operation1': function() {
console.log('Executing operation 1');
},
'operation2': function() {
console.log('Executing operation 2');
},
'operation3': function() {
console.log('Executing operation 3');
}
};
// 客户端代码
function executeStrategy(strategyName) {
const strategy = strategies[strategyName];
if (strategy) {
strategy();
} else {
console.log('Invalid strategy');
}
}
// 使用策略模式执行不同操作
executeStrategy('operation1'); // 执行operation1
executeStrategy('operation2'); // 执行operation2
executeStrategy('operation3'); // 执行operation3
executeStrategy('operation4'); // 打印"Invalid strategy"