专栏名称: SegmentFault思否
SegmentFault (www.sf.gg)开发者社区,是中国年轻开发者喜爱的极客社区,我们为开发者提供最纯粹的技术交流和分享平台。
目录
相关文章推荐
OSC开源社区  ·  2024: 大模型背景下知识图谱的理性回归 ·  2 天前  
程序猿  ·  “未来 3 年内,Python 在 AI ... ·  3 天前  
程序员的那些事  ·  成人玩偶 + ... ·  3 天前  
程序员小灰  ·  DeepSeek做AI代写,彻底爆了! ·  3 天前  
程序员的那些事  ·  李彦宏自曝开源真相:从骂“智商税”到送出“史 ... ·  4 天前  
51好读  ›  专栏  ›  SegmentFault思否

深入浅出 js 中的策略模式

SegmentFault思否  · 公众号  · 程序员  · 2020-03-03 11:51

正文

本文转载于 SegmentFault 社区
作者:chinamasters


什么是策略模式,官方定义是:定义一些列算法,把他们封装起来,并且可以相互替换。

说句话: 就是把看似毫无联系的代码提取封装、复用,使之更容易被理解和拓展 。常见的用于一次 if 判断、switch 枚举、数据字典等流程判断语句中。



使用策略模式计算等级



在游戏中,我们每玩完一局游戏都有对用户进行等级评价,比如 S 级 4 倍经验,A 级 3 倍经验,B 级 2 倍经验,其他 1 倍经验,用函数来表达如下:
function getExperience(level, experience){
if(level == 'S'){
return 4*experience
}
if(level == 'A'){
return 3*experience
}
if(level == 'B'){
return 2*experience
}
return experience
}
可知 getExperience 函数各种 if 条件判断,复用性差,我们根据策略模式封装复用的思想,进行改写。

// 改为策略模式 分成两个函数来写
const strategy = {
'S' : function(experience){
return 4*experience
},
'A' : function(experience){
return 3*experience
},
'B' : function(experience){
return 2*experience
}
}
// getExperience可以复用
function getExperience(strategy, level, experience){
return (level in strategy) ? strategy[level](experience) : experience
}
var s = getExperience(strategy, 'S', 100)
var a = getExperience(strategy, 'A', 100)
console.log(s, a) // 400 300
分为两个函数之后,strategy 对象解耦,拓展性强。在 vue 数据驱动视图更新的更新器 updater 使用,就使用了策略模式。想要进一步了解 vue 底层原理,可以参考可以参考 github 上的一篇文章 ☛ MVVM 实现。

// 指令处理集合
var compileUtil = {
// v-text更新视图原理
text: function(node, vm, exp) {
this.bind(node, vm, exp, 'text');
},
// v-html更新视图原理
html: function(node, vm, exp) {
this.bind(node, vm, exp, 'html');
},
// v-class绑定原理
class: function(node, vm, exp) {
this.bind(node, vm, exp, 'class');
},
bind: function(node, vm, exp, dir) {
// 不同指令触发视图更新
var updaterFn = updater[dir + 'Updater'];
updaterFn && updaterFn(node, this._getVMVal(vm, exp));
new Watcher(vm, exp, function(value, oldValue) {
updaterFn && updaterFn(node, value, oldValue);
});
}
......
}


使用策略模式验证表单


常见表单验证用 if、else 流程语句判断用户输入数据是否符合验证规则,而在 Elementui 中,基于 async-validator 库,只需要通过 rule 属性传入约定的验证规则,即可校验。方便快捷,可复用。现在我们根据策略模式仿写一个校验方式。

// 我们写一个form表单
"/" class="form">
type="text" name="username">
type="password" name="password">
submit

id="tip">

首先定义校验规则
const strategies = {
// 非空
noEmpty: function(value, errMsg){
if(value === ''){
return errMsg
}
},
// 最小长度
minLength: function(value, length, errMsg){
if(!value || value.length < length){
return errMsg
}
},
// 最大长度
maxLength: function(value, length, errMsg){
if(value.length > length){
return errMsg
}
}
}

接着设置验证器
// 创建验证器
var Validator = function(strategies){
this.strategies = strategies
this.cache = [] // 存储校验规则
}
// 添加校验规则
Validator.prototype.add = function(dom, rules){
rules.forEach(item => {
this.cache.push(() => {
let value = dom.value
let arr = item.rule.split(':')
let name = arr.shift()
let params = [value, ...arr, item.errMsg]
// apply保证上下文一致
return this






请到「今天看啥」查看全文