JavaScript 设计模式之策略模式

作者: tww844475003 分类: 前端开发 发布时间: 2021-06-06 19:23

定义:定义一系列的算法,把它们一个个封装起来,并且使它们可以相互替换

这些算法灵活多样,而且可以随意互相替换
var strategies = {
  'S': function(salary) {
    return salary * 4
  },
  'A': function(salary) {
    return salary * 3
  },
  'B': function(salary) {
    return salary * 2;
  }
}

var calculateBonus = function(level, salary) {
  return strategies[level](salary);
}

console.log(calculateBonus('S', 20000)); // 80000
console.log(calculateBonus('A', 10000)); // 30000
console.log(calculateBonus('B', 10000)); // 20000

使用策略模式封装表单输入框的校验规则

<form action="https://www.ifrontend.net/register" id="registerForm" method="POST">
  请输入用户名:<input type="text" name="userName" />
  请输入密码:<input type="text" name="password" />
  请输入手机号码:<input type="text" name="phoneNumber" />
  <button>提交</button>
</form>
<script>
var strategies = {
  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[3|5|8][0-9]{9}$)/.test(value)) {
      return errorMsg;
    }
  }
};

var Validator = function() {
  this.cache = [];
};
Validator.prototype.add = function(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.value);
        strategyAry.push(errorMsg);
        return strategies[strategy].apply(dom, strategyAry);
      })
    })(rule);
  }
}

Validator.prototype.start = function() {
  for (var i = 0, validatorFunc; validatorFunc = this.cache[i++];) {
    var errorMsg = validatorFunc();

    if (errorMsg) {
      return errorMsg;
    }
  }
}

var registerForm = document.getElementById('registerForm');
var validataFunc = function() {
  var validator = new Validator();

  validator.add(registerForm.userName, [{
    strategy: 'isNonEmpty',
    errorMsg: '用户名不能为空'
  }, {
    strategy: 'minLength:10',
    errorMsg: '用户名长度不能小于10位'
  }]);

  validator.add(registerForm.password, [{
    strategy: 'isNonEmpty',
    errorMsg: '密码不能为空'
  }, {
    strategy: 'minLength:6',
    errorMsg: '密码长度不能小于6位'
  }]);

  validator.add(registerForm.phoneNumber, [{
    strategy: 'isMobile',
    errorMsg: '手机号码格式不正确'
  }]);

  var errorMsg = validator.start();
  return errorMsg;
}

registerForm.onsubmit = function() {
  var errorMsg = validataFunc();

  if (errorMsg) {
    console.log(errorMsg);
    return false;
  }

  return false;
}
</script>  

前端开发那点事
微信公众号搜索“前端开发那点事”

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注