策略模式的定义
- 定义一系列的算法 将他们封装起来 并且他们之间可以相互替换
- 核心:将算法的使用 和 算法的实现 分离
案例:绩效为 S的人年终奖有4倍公司,为A年终奖有3倍,B为2倍
var pS = function () { }
pS.prototype.calculate = function (salary) {
return salary * 4
}
var pA = function () { }
pA.prototype.calculate = function (salary) {
return salary * 3
}
var pB = function () { }
pB.prototype.calculate = function (salary) {
return salary * 2
}
var Bouns = function () {
this.salary = null
this.strategy = null
}
Bouns.prototype.setSalary = function (salary) {
this.salary = salary
}
Bouns.prototype.setStrategy = function (strategy) {
this.strategy = strategy
}
Bouns.prototype.getBouns = function () {
return this.strategy.calculate(this.salary)
}
var bouns = new Bouns()
bouns.setSalary(10000)
bouns.setStrategy(new pS())
console.log(bouns.getBouns())
var strategies = {
"S": function (salary) {
return salary * 4
},
"A": function (salary) {
return salary * 3
},
"B": function (salary) {
return salary * 2
},
}
var getBouns = function (level, salary) {
return strategies[level](salary)
}
console.log(getBouns('S', 10000))
案例:表单验证
var registerForm = document.getElementById('registerForm')
registerForm.onsubmit = function () {
if (registerForm.username.value == ''){
alert('用户名不为空')
return false
}
if (registerForm.password.value.length < 6){
alert('密码不能小于6')
return false
}
if (!/^1[3|5|8][0-9]{p}$/.test(registerForm.phonenumber.value)){
alert('手机号格式不正确')
return false
}
}
策略模式封装
var strategies = {
isNonEmpty: function (value, errorMsg) {
if (value == ''){
return errorMsg
}
},
minLength: function (value, length, errorMsg) {
if (value.length < 6){
return errorMsg
}
},
isMobile: function (value, errorMsg) {
if (!/^1[3|5|8][0-9]{p}$/.test(value)){
return errorMsg
}
},
}
var validateFun = function () {
var validator = new Validator()
validator.add(registerForm.username, 'isNonEmpty', '用户名不能为空')
validator.add(registerForm.username, 'minLength:6', '密码长度不能小于6位')
validator.add(registerForm.username, 'isMobile', '手机号格式不正确')
var errorMsg = validator.start()
return errorMsg
}
registerForm.onsubmit = function () {
var errorMsg = validateFun()
if (errorMsg){
alert(errorMsg)
return false
}
}
var Validator = function () {
this.cache = []
}
Validator.prototype.add = function (dom, rule, errorMsg) {
var ary = rule.split(':')
this.cache.push(function () {
var strategy = ary.shift()
ary.unshift(dom.value)
ary.push(errorMsg)
return strategies[strategy](...ary)
})
}
Validator.prototype.start = function () {
for (var i = 0, vaFunc; vaFunc = this.cache[i++];){
var msg = vaFunc()
if(msg){
return msg
}
}
}