# 读书笔记之策略模式

``````var calc = function(level,salary){
if(level === "A"){
return 3*salary
}
if(level === "B"){
return 2*salary
}
if(level === "C"){
return 1*salary
}
}``````

• 策略模式指的是定义一系列的算法，把他们一个个都封装起来。将不变的部分和变化的部分分割开始每个设计模式的主题，策略模式的目的就是将算法的使用与算法的实现分离开来。

• 再说上边的需求，我们简单思考下，其实变化的部分就是员工的等级和工资,而我们的目的就是返回绩效工资这部分是不变的

``````//  根据员工的level和salary 金额的计算
var straigies = {
“A”: function(salary){
return fn*3
},
“B”: function(salary){
return fn*2
},
“C”: function(salary){
return fn*1
}
}
//不变的部分
var calc = function(level,salary){
return straigies[level](salary)
}
// 执行
calc("A",5000)    // => 15000``````

• 用策略模式来重构表单验证

``````\$('submitBtn').on('click',functioin(){
if(\$name.value().length < 6){
console.log("用户名长度不能少于6")
}
if(\$phone.value() != ''){
console.log("电话号码不能为空")
}
ajaxFn()
})``````

``````\$('submitBtn').on('click',functioin(){
var form = document.querySelector('.form');
var validator = new validator ();
var erroMsg = validator.start();
if(erroMsg){
return false
}
ajaxFn()
})``````

``````var stratigies = {
isNonEmpty: function(value,erromsg){
if(value == ""){
return erromsg
}
},
minlength: function(value,length,erromsg){
if(value.length < length){
return erromsg
}
}
}``````

``````var Validator = function(){
this.cache = [] //用来缓存
}
var arg = rule.split(":") // rule= >  "isEmpty" => ["isEmpty"] ||  "minLength:5"=> ["minlength", “5”];
this.cache.push(function(){
var strategy = arg.shift();  // =>"isEmpty" || minLength
arg.unshift(item.value);  //[value] || [value,5]
arg.push(errMsg)// [value,errMsg] || [value,5,errMsg]
return  stratigies[strategy].apply(item,arg)
})
}
//start方法就是遍历这个Validator里缓存的方法并执行
Validator.prototype.start = function(){
for(var i=0;i开始校验，
if(msg){
return msg   // 如果msg有值 就说明验证不通过，跳出循环
}
}
}``````

``validator.addrules(form.phone,"minLength:6") =》 validator.addrules(form.phone,"minLength:10")``

``````//预期
{
"erroMsg": "不能为空",
"strategy": 'isNonEmpty'
},
{
"erroMsg": "最小为6位",
"strategy": 'minLength:6'
}
])``````

``````//old type
var arg = rule.split(":") // rule= >  "isEmpty" => ["isEmpty"] ||  "minLength:5"=> ["minlength", “5”];
this.cache.push(function(){
var strategy = arg.shift();  // =>"isEmpty" || minLength
arg.unshift(item.value);  //[value] || [value,5]
arg.push(errMsg)// [value,errMsg] || [value,5,errMsg]
return  stratigies[strategy].apply(item,arg)
})
}
// new Type
var  _this = this; //保存this指针   for循环里的的自执行函数的this指向window，用_this修复指针
//遍历rules
for(var i = 0;i  "isEmpty" => ["isEmpty"] ||  "minLength:5"=> ["minlength", “5”];
var  errMsg = rule.errMsg;
_this.cache.push(function(){
var strategy = arg.shift();  // =>"isEmpty" || minLength
arg.unshift(item.value);  //[value] || [value,5]
arg.push(errMsg)// [value,errMsg] || [value,5,errMsg]
return  stratigies[strategy].apply(item,arg)
})
})(rule)
}
}``````