Learn the strategy patterns of JavaScript design patterns

  • 2020-11-30 08:09:31
  • OfStack

Separating the unchanging from the changing is the theme of every design pattern.

All roads lead to Rome. We often come across multiple solutions to one thing, such as compressed files. We can use zip or gzip. Its flexibility and diversity, we can use the strategy pattern to solve.

Definition 1.

Define a series of 1 algorithms, encapsulate each of them, and make them interchangeable.
A program based on the policy class pattern consists of at least two parts. The first part is a set of policy classes that encapsulate the specific algorithm and are responsible for the specific calculation process. The second part is the environment class Context, which receives the customer's request and then delegates the request to one of the policy classes.

Example 2.

Calculate bonuses. Performance is paid 4 times of S, performance is paid 3 times of A, and performance is paid 2 times of B.


var strategies = {
 "S": function(salary) {
  return salary * 4;
 },
 "A": function(salary) {
  return salary * 3;
 },
 "B": function(salary) {
  return salary * 2;
 }
};

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

//  test 
console.log(calculateBonus("S", 20000));
console.log(calculateBonus("A", 20000));
console.log(calculateBonus("B", 20000));

3. Extension: Form validation


/*  Check policy object  */
var validateStrategies = {
 isEmpty: function (val, errorMsg) {
  if (!val) {
   return errorMsg;
  }
 },
 isURL: function (val, errorMsg) {
  if (!new RegExp("^(http:\\/\\/|https:\\/\\/)?([\\w\\-]+\\.)+[\\w\\-]+(\\/[\\w\\-\\.\\/?\\@\\%\\!\\&=\\+\\~\\:\\#\\;\\,]*)?$").test(val)) {
   return errorMsg;
  }
 },
 isEmail: function (val, errorMsg) {
  if (!new RegExp('\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+').test(val)) {
   return errorMsg;
  }
 },
 isMaxLength: function (val, length, errorMsg) {
  if (val.length > length) {
   return errorMsg;
  }
 },
 isMinLength: function (val, length, errorMsg) {
  if (val.length < length) {
   return errorMsg;
  }
 }
};

/* validator class  */
var validator = function () {
 //  Cache validation strategy 
 this.cache = [];
};

/**
 *  Add the policy to validate 
 * @param dom   To verify the dom The element 
 * @param rules   The validation rules 
 */
validator.prototype.add = function (dom, rules) {
 var self = this;
 for (var i = 0, rule; rule = rules[i++];) {
  (function (rule) {
   var strategyAry = rule.strategy.split(":");  // ["isMaxLength", "10"]
   var errorMsg = rule.errorMsg;     // " The content length must not exceed 10"
   self.cache.push(function () {
    var strategy = strategyAry.shift();   // "isMaxLength"
    strategyAry.unshift(dom.value);    // ["1@qq", "10"]
    strategyAry.push(errorMsg);     // ["1@qq", "10", " The content length must not exceed 10"]
    return validateStrategies[strategy].apply(dom, strategyAry);
   });
  })(rule);
 }
};

/*  Begin to check  */
validator.prototype.start = function () {
 for (var i = 0, validateFunc; validateFunc = this.cache[i++];) {
  var errorMsg = validateFunc();
  if (errorMsg) {
   return errorMsg;
  }
 }
};


//  test 

<label for="email"> Email address: </label><input type="text" name="email" value="1@qq">

var validatorInstance = new validator();
validatorInstance.add(
 document.getElementsByName("email")[0], 
 [{
  strategy: "isEmpty",
  errorMsg: " The content cannot be empty "
 },{
  strategy: "isMaxLength:10",
  errorMsg: " The content length must not exceed 10"
 },{
  strategy: "isEmail",
  errorMsg: "email Format is wrong "
 }]);
errorMsg = validatorInstance.start();

I hope this article has been helpful in learning javascript programming.


Related articles: