Javascript:设计模式-策略模式
//场景设定: 员工等级分为ABC级,根据不通等级传入基础工资 = 年终奖
var calculate = function(Level, money) { let num if (Level === 'A') { num = money * 4 } else if (Level === 'B') { num = money * 3 } else if (Level === 'C') { num = money * 2 }}calculate('B', 20000) |
// 重构一下
var performanceC = function(money) { return money * 2}var performanceA = function(money) { return money * 4}var performanceB = function(money) { return money * 3}var calculate = function(Level, money) { if (Level === 'A') { return performanceA(money) } else if (Level === 'B') { return performanceB(money) } else if (Level === 'C') { return performanceC(money) }} |
// 组合函数重构:可以一目了然地知道它对应着哪种算法,它们也可以被复用在程序的其他地方。
// 公司扩张了,每个部门年终奖分为了10个等级
let numif (level === 'A') { num = money * 4} else if (level === 'B') { num = money * 3} else if (level === 'C') { num = money * 2} else if (level === 'D') { num = money * 2} else if (level === 'E') { num = money * 2} else if (level === 'F') { num = money * 2} else if (level === 'G') { num = money * 2} else if (level === 'H') { num = money * 2} else if (level === 'I') { num = money * 2} else if (level === 'J') { num = money * 2}// else if..... |
// JS毕竟是面向对象语言,封装成对象,等级变为Key值,
// 策略模式:strategy对象从各个策略类中创建而来,这是模拟一些传统面向对象语言的实现。
// 实际上在JavaScript语言中,函数也是对象,所以更简单和直接的做法是把strategy直接定义为函数
// 做什么(策略对象算法)
const strategies = { C: function(money) { return money * 2 }, A: function(money) { return money * 4 }, B: function(money) { return money * 3 }} |
// 谁去做(策略对象)
const calculate = function(level, money) { // 返回不同计算结果,这正是多态的体现 return strategies[level](money)} |
// 对对象发出计算请求calculate('C', 20000)calculate('A', 6000) |
// 策略模式的优缺点
// 策略模式是一种常用且有效的设计模式,我们可以总结出策略模式的一些优点。
// 策略模式利用组合、委托和多态(将做什么和谁去做分离开,也就是将不变的事与可能变得事分离开)等技术和思想,
// 可以有效地避免多重条件选择语句,让程序看起来是可生长的。
// 策略模式提供了对开放—封闭原则的完美支持,将算法封装在独立的strategy中,使得它们易于切换,易于理解,易于扩展。
// 策略模式中的算法也可以复用在系统的其他地方,从而避免许多重复的复制粘贴工作。
// 要使用策略模式,必须了解所有的strategy,
// 必须了解各个strategy之间的不同点,这样才能选择一个合适的strategy。
// 比如,我们要选择一种合适的旅游出行路线,必须先了解选择飞机、火车、自行车等方案的细节。
// 此时strategy要向客户暴露它的所有实现,这是违反最少知识原则的。
// 除了策略模式还有很多其他的设计模式
// 单例,代理,迭代器,订阅者,命令模式等...
// 订阅者模式多提一句
// 像咱们用的Vue2.0,就是用的Object.defineProperty(),来劫持发布消息给订阅者,触发相应监听回调
// 知道了这个以后就能知道为什么Vue数组下标来设置值老是不能实时响应
// 感兴趣可以看一下他具体实现方法而Vue3.0则改为了Proxy代理,效率更高更简洁
浙公网安备 33010602011771号