定义
要实现某一功能有多种方案可以选择;可以定义策略把它们一个个封装起来,并且使它们可以相互转换
场景
当场景中存在多个if或多个if-else时可以使用策略模式
像表单元素中内容的校验、登录用户的权限验证
// 策略模式
// 策略
const strategies = {
// 字符串
// 不为空
isEmpty: (value, errorMsg) => {
return value !== '' ? '' : errorMsg
},
// 最小长度限制
limitLength: (value, errorMsg, minLength) => {
return value.length > minLength ? '' : errorMsg
},
// 只能是汉字
isChinese: (value, errorMsg) => {
return /[\u4E00-\u9FA5]/g.test(value) ? '' : errorMsg
},
// 验证手机号
phoneNumber: (value, errorMsg) => {
return /^1[]/g.test(value) ? '' : errorMsg
},
// 验证邮箱
// 验证身份证号码
// 屏蔽关键字
// 数字
// 最小值
gtMin: (value, errorMsg, minVal) => {
return value > minVal ? '' : errorMsg
},
// 最大值
ltMax: (value, errorMsg, maxVal) => {
return value < maxVal ? '' : errorMsg
},
}
// 校验规则
const Validator = function() {
this.cache = []
this.msg = []
// 添加
this.addValidatorEvent = function(value, method, errorMsg, ...args) {
this.cache.push(function () {
return strategies[method](value, errorMsg, ...args)
})
}
// 检查
this.checkData = function() {
this.cache.map((item) => {
this.msg.push(item())
})
return this.msg
}
}
let validator = new Validator()
validator.addValidatorEvent('', 'isEmpty', '该项不能为空')
validator.addValidatorEvent('123', 'isChinese', '只能是汉字')
validator.addValidatorEvent(22, 'gtMin', '最小值为25', 25)
validator.addValidatorEvent(18, 'ltMax', '最大值为20', 20)
validator.addValidatorEvent('faf', 'limitLength', '字符串最小长度为5', 5)
let res = validator.checkData()
console.log(res)
输出
["该项不能为空", "只能是汉字", "最小值为25", "", "字符串最小长度为5"]
使用者可根据返回该项的值是否为空字符串来给用户输入提示