Skip to content

策略模式 ​

策略模式是把一系列的算法或业务逻辑封装起来,它们可互相替换使用。

具体由策略类和环境类组成,策略类封装了各种具体算法,而环境类 Context 用于接收请求,然后把请求委托给某个策略。

策略模式优点:

  • 避免了多个 if 条件判断,易于扩展。
  • 符合开发-封闭原则。
  • 策略可在其他地方复用。

策略类 ​

以表单校验为例,创建策略类。

js
const strategies = {
  isNonEmpty(value, errorMsg) {
    if (value === '') {
      return errorMsg
    }  
  },
  minLength(value, length, errorMsg) {
    if (value.length < length) {
      return errorMsg
    }  
  }
}

环境类 ​

js
class Validator {
  cache = []
  
  add(dom, rule, errorMsg) {
    const ary = rule.split(':')
    const validFn = function () {
      const strategy = ary.shift() // 具体策略
      ary.unshift(dom.value)       // 表单控件的值
      ary.push(errorMsg)
      return strategies[strategy].apply(dom, ary)
    }
    this.cache.push(validFn)
  }
  
  start() {
    for (let i = 0; i < this.cache.length; i++) {
      const validFn = this.cache[i]
      const msg = validFn()
      if (msg) { // 若有返回值则表示校验未通过
        return msg
      }
    }
  }
}

配置 ​

通过配置的方式进行使用。

js
function validateFn() {
  const validator = new Validator()
  
  validator.add(form.userName, 'isNonEmpty', '用户名不可为空')
  validator.add(form.password, 'minLength:6', '密码长度不可少于6位')
  
  const errorMsg = validator.start()
  return errorMsg
}  
  
const form = document.getElementById('form')
form.onsubmit = function () {
  const errorMsg = validateFn()
  if (errorMsg) {
    console.log(errorMsg)
    return false // 阻止表单提交
  }
}

若同一表单项要校验多条规则,策略对象里换成数组,再修改下 add 和 start 方法即可。