zhangdizhangdi

策略模式 ⭐

定义

策略模式(Strategy Pattern),定义一系列的算法,把它们一个个封装起来,并且使它们可以相互替换。

实现

js
//年终奖
const strategies = {
  S: function (salary) {
    return salary * 4
  },
  A: function (salary) {
    return salary * 3
  },
  B: function (salary) {
    return salary * 2
  },
}
const calculateBonus = function (level, salary) {
  return strategies[level](salary)
}
console.log(calculateBonus('S', 20000)) // 输出:80000
console.log(calculateBonus('A', 10000)) // 输出:30000
执行结果
80000
30000
js
;<form id="registerForm">
  <input name="userName" value="111" />
  <input name="phoneNumber" value="22243344" />
  <input name="password" value="22243344" />
</form>

//表单校验
const formStrategies = {
  isNonEmpty: function (value, errorMsg) {
    if (value === '') {
      return errorMsg
    }
  },
  minLength: function (value, length, errorMsg) {
    if (value.length < length) {
      return errorMsg
    }
  },
  isMobile: function (value, errorMsg) {
    if (!/(^1[0-9]{10}$)/.test(value)) {
      return errorMsg
    }
  },
}
const Validator = function () {
  this.cache = []
}
Validator.prototype.add = function (dom, rule, errorMsg) {
  let ary = rule.split(':')
  this.cache.push(function () {
    const strategy = ary.shift()
    ary.unshift(dom.value)
    ary.push(errorMsg) //
    return formStrategies[strategy].apply(dom, ary)
  })
}
Validator.prototype.start = function () {
  for (var i = 0, validatorFunc; (validatorFunc = this.cache[i++]); ) {
    var msg = validatorFunc()
    if (msg) {
      return msg
    }
  }
}
const validataFunc = function () {
  const validator = new Validator()
  validator.add(registerForm.userName, 'isNonEmpty', '用户名不能为空')
  validator.add(registerForm.password, 'minLength:6', '密码长度不能少于 6位')
  validator.add(registerForm.phoneNumber, 'isMobile', '手机号码格式不正确')
  var errorMsg = validator.start()
  return errorMsg
}

const registerForm = document.getElementById('registerForm')
registerForm.onsubmit = function () {
  const errorMsg = validataFunc()
  if (errorMsg) {
    console.log(errorMsg)
    return false
  }
}
registerForm.onsubmit()

参考