js设计模式——策略模式

js设计模式——策略模式,第1张

以验证对象属性为例,直接上代码,文字少 了还不让发。多写几个字。。。。

// 创建策略
const DICT = {
  isEmpty:(...args) => {
    const [v, msg] = args
    if(v === '') {
      console.log(msg)
      throw new Error(msg)
    }
  },
  minLength:(...args) => {
    const [v,len, msg] = args
    if(v.length < len) {
      console.log(msg)
     throw  new Error(msg)
    }
  }
}
// 创建验证管理类
class validate {
  constructor() {
    this.arr = [];
  }
  add(...args){
    const [rule, ...ops]  = args
    this.arr.push(() => {
      DICT[rule](...ops)
    })
  }
  start(){
    let status = true
    for(let i = 0; i< this.arr.length ;i++) {
      try{
        this.arr[i]()
      } catch(err) {
        status = false
        break;
      }
    }
    return status
  }
}
//实例化管理类
const o = new validate()

function start() {
  let obj = {
    name:'1',
    pass: '1'
  }
  // 为管理类添加策略
  o.add('isEmpty',obj.name,'用户名不得为空')
  o.add('isEmpty',obj.pass,'密码名不得为空')
  o.add('minLength','aa二44',5,'长度不能小于5')
  if(o.start()) {
    console.log('验证通过')
  } else {
    console.log('验证没通过')
  }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/944111.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-18
下一篇 2022-05-18

发表评论

登录后才能评论

评论列表(0条)

保存