This is the fifth day of my participation in the August Wen Challenge.More challenges in August

Definition of policy patterns

Define a set of algorithms, encapsulate them one by one, and make them interchangeable.

The purpose of the policy pattern is to separate the use of algorithms from the implementation of algorithms. A policy-based program consists of at least two parts. The first part is a set of policy classes, which encapsulate the specific algorithm and are responsible for the specific calculation process. The second part is the Context class, which accepts a client’s request and then delegates it to a policy class.

A policy pattern is defined by defining a set of algorithms and encapsulating them individually into a policy class. The algorithms are encapsulated in methods within the policy class. When a client makes a request to the Context, the Context always delegates the request to one of these policy objects for calculation.

Application scenarios of the policy mode

The application scenarios of the policy pattern are actually quite broad. If there are multiple options for a function to be implemented, then it is suitable to use the policy pattern to implement it.

Here we list a few common application scenarios and explain them:

Based on the employee’s salary base M and year-end performance (S, A…) To determine year-end bonuses

For a single employee, the salary base is fixed, and the year-end performance corresponds to the year-end bonus algorithm of each grade according to the grade obtained. Here, the strategy class is the method combination of the year-end bonus calculation formula corresponding to each performance, while the environment class selects the corresponding calculation formula according to the performance of the employee.

Slow animation using strategy mode

The policy class is different animation motion rules (linear, slow in, slow out, etc.), while the environment class contains methods responsible for common startup, update, etc., each method calls motion rules as needed.

Form validation

The policy class is a combination of different validation methods, while the environment class provides data caching and validation steps.

Advantages and disadvantages of strategic patterns

Advantages:

  • Using techniques and ideas such as composition, delegation, and polymorphism, you can effectively avoid multiple judgment statements (eliminate multiple if-else)
  • Provides perfect support for the open closed principle, encapsulating algorithms in separate policy classes, making them easy to switch, easy to understand, and easy to extend
  • Algorithms in the policy pattern can also be reused elsewhere, avoiding a lot of repetitive copy-and-paste work
  • Use composition and delegation to give the Context Context the ability to perform the algorithm

Disadvantages:

  • Using the policy pattern adds a lot of policy classes to your program, which simply means more code, but is actually better than stacking this logic in the Context
  • To use the policy pattern, you must understand all the policy methods so that you can choose the most appropriate one to use. At this point, the policy class must expose all of its implementations, which violates the least knowledge rule.

Analysis of the implementation principle of strategy pattern

Next, let’s analyze the implementation idea of policy mode applied to form verification:

  • Clarify the validation logic (the username cannot be empty and the password must be at least 6 characters);
  • Encapsulate policy classes based on validation logic
  • Next, we need to implement the environment class. In order to better write the environment class, we know in advance how the user sends the request to the environment class, write the calling code
  • Implement the environment class based on the previous call

Concrete implementation of the code

Start by writing out the HTML form code for validation

<form action="http:// xxx.com/register" id="registerForm" method="post">Please enter user name:<input type="text" name="userName"/ >Please enter your password:<input type="text" name="password"/ >
    <button>submit</button>
</form>
Copy the code

To better understand the benefits of the policy pattern, here is a comparison of the code before and after using the policy pattern.

Before using policy mode:

var form = document.getElementById('registerForm');

form.onsubmit = function() {
    // The more rules there are, the more if there is
    if(form.userName.value === ' ') {
        alert('User name cannot be empty');
        return false;
    }
    if(form.password.value.length < 6) {
        alert('Password length must not be less than 6 characters');
        return false; }}Copy the code

After using policy mode:

// Implement the policy class
var strategies = {
    isNonEmpty: function(v, msg) {
        if(v === ' ') return msg;
    },
    minLength: function(v, l, msg) {
        if(v.length < l) returnmsg; }};// The implementation of the environment class
var Context = function(){
    this.cache = [];
};
Context.prototype.add = function(d, method, msg) {
    var ary = method.split(':'); // Consider the case of validating the password length
    this.cache.push(function() {
       var strategy = ary.shift(); 
       ary.unshift(d.value);
       ary.push(msg);
       // Returns the result of the call to the policy class
       return strategies[strategy].apply(d, ary);
    });
};
Context.prototype.start = function() {
    // Loop to validate the configured rule
    for(var i = 0, func; func = this.cache[i++]) {
        var msg = func();
        if(msg) returnmsg; }};// when the user calls
var form = document.getElementById('registerForm');
var vFunc = function() {
    var validator = new Context();
    
    validator.add(form.userName, 'isNonEmpty'.'User name cannot be empty');
    validator.add(form.password, 'minLength:6'.'Password length must not be less than 6 characters');
    
    var msg = validator.start();
    return msg;
};
form.onsubmit = function() {
    var msg = vFunc();
    if(msg) return msg;
};
Copy the code