js设计模式之策略模式

https://segmentfault.com/a/1190000017721211

// 在这里写
var strategies = {
  isNonEmpty(value, errorMsg) {
    if (value === "") {
      return errorMsg;
    }
  },
  minLength(value, length, errorMsg) {
    if (value.length < length) {
      return errorMsg;
    }
  },
  isMobile(value, errorMsg) {
    if (!/(^1[3|5|8][0-9]{9}$)/.test(value)) {
      return errorMsg;
    }
  },
  moreThan(value, errorMsg) {
    console.log("a", value);
    if (parseInt(value[0]) < parseInt(value[1])) {
      return errorMsg;
    }
  },
};
class Validator {
  constructor() {
    this.cache = [];
  }

  add(dom, rules) {
    var self = this;
    for (var i = 0, rule; (rule = rules[i++]); ) {
      (function (rule) {
        var strategyAry = rule.strategy.split(":");
        var errorMsg = rule.errorMsg;
        self.cache.push(function () {
          var strategy = strategyAry.shift();
          strategyAry.unshift(dom);
          strategyAry.push(errorMsg);
          return strategies[strategy].apply(self, strategyAry);
        });
      })(rule);
    }
  }
  start() {
    for (var i = 0, validatorFunc; (validatorFunc = this.cache[i++]); ) {
      var errorMsg = validatorFunc();
      if (errorMsg) {
        return errorMsg;
      }
    }
  }
}
原文地址:https://www.cnblogs.com/TTblog5/p/13159147.html