使用简单的策略模式处理多个 if 和 else 语句

118 阅读1分钟

使用简单的策略模式处理多个 if 和 else 语句

策略模式是一种行为设计模式,它将一组行为封装到一系列的策略对象中。在运行时,你可以使用这些策略对象来改变程序的行为。这使得你的代码更加模块化,易于测试和维护。

当你的代码中存在多个 if 和 else 语句时,你可以使用策略模式来简化你的代码。

以下是一个基本的策略模式的实现:

在 strategyManager.js 中:

// 初始化策略对象,包含预定义的策略
let strategies = {
  'greaterThan': (a, b) => a > b, // 大于策略
  'lessThan': (a, b) => a < b, // 小于策略
};

// 添加新的策略到策略对象
function addStrategy (type, strategy) {
  strategies [type] = strategy; // 将新的策略函数添加到策略对象
}

// 执行特定的策略,如果没有找到对应的策略,则执行默认策略
function executeStrategy (type, defaultStrategy, ...args) {
  const strategy = strategies [type]; // 从策略对象中获取特定的策略
  if (strategy) {
    return strategy (...args); // 如果找到了策略,则执行它
  } else {
    // 如果没有找到策略,则执行默认策略
    return defaultStrategy (...args);
  }
}

// 导出函数,以便在其他模块中使用
module.exports = {
  addStrategy,
  executeStrategy
};

使用 都是等于xx的情况下

const { addStrategy, executeStrategy } = require ('./strategyManager');
// 添加策略
addStrategy ('0', () => {
    console.log("这是走的判断0")
});

addStrategy ('1', () => {
   console.log("这是走的判断1")
});

// 默认策略  else
const defaultStrategy =()=>{
    console.log("这是走的else")
}

//使用
const id = 0;
executeStrategy(id,defaultStrategy);


使用 大于、小于或者等于xx的情况下

// 添加新的策略
addStrategy ('equals', (a, b) => a === b);

const defaultStrategy =()=>{
    console.log("不用管")
}
console.log(executeStrategy('greaterThan', defaultStrategy, 5, 3)) //输出:true
console.log(executeStrategy('lessThan', defaultStrategy, 5, 3)) //输出:false
console.log(executeStrategy('equals', defaultStrategy, 5, 5)) //输出:true