Here is a concise front-end knowledge system waiting for you to check, have a look, there will be a surprise oh, if you feel good, begged star ha ~


Overview of Policy Patterns

The policy pattern defines a series of algorithms, encapsulates them one by one, and makes them interchangeable.

The advantages of policy mode are as follows: (1) Policy mode can effectively avoid many if conditional statements; (2) Policy mode conforms to the open-closed principle, making the code easier to understand and expand; (3) Code in policy mode can be reused

Practice a

Take the company’s annual bonus as an example: 1. The annual bonus of A person is 4 times the salary; the annual bonus of B person is 3 times the salary; the annual bonus of C person is 2 times the salary

Traditional solutions

var calculateBouns = function(salary,level) {
    if(level === 'A') {
        return salary * 4;
    }
    if(level === 'B') {
        return salary * 3;
    }
    if(level === 'C') {
        returnsalary * 2; }}; Console. log(calculateBouns(4000,'A')); // 16000
console.log(calculateBouns(2500,'B')); / / 7500Copy the code

The drawbacks of the above code are: 1. CalculateBouns function contains many if-else statements. Ii. CalculateBouns function is inelastic. If there is still grade D, we need to add an IF statement to judge grade D in calculateBouns function. Third, the algorithm reuse is poor, if there is a similar algorithm in other places, but the rules are not the same, our code can not be general.

Refactoring code using composition functions

var performanceA = function(salary) {
    return salary * 4;
};
var performanceB = function(salary) {
    return salary * 3;
};
        
var performanceC = function(salary) {
    return salary * 2
};
var calculateBouns = function(level,salary) {
    if(level === 'A') {
        return performanceA(salary);
    }
    if(level === 'B') {
        return performanceB(salary);
    }
    if(level === 'C') {
        returnperformanceC(salary); }}; // Call console.log(calculateBouns('A', 4500)); / / 18000Copy the code

The code looks a little better, but there are drawbacks: The calculateBouns function can get bigger and bigger, for example when the D level is increased, and it is inflexible.

Refactoring code using policy patterns

The strategy pattern refers to defining a series of algorithms, encapsulating them one by one, separating the invariable parts from the changing parts, in effect separating the use and implementation of the algorithm.

A program based on policy pattern 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 environment class Context, which receives client requests and then delegates them to a policy class.

var obj = {
        "A": function(salary) {
            return salary * 4;
        },
        "B" : function(salary) {
            return salary * 3;
        },
        "C" : function(salary) {
            returnsalary * 2; }}; var calculateBouns =function(level,salary) {
    return obj[level](salary);
};
console.log(calculateBouns('A', 10000)); / / 40000Copy the code

Practice 2

Form validation is a very common feature. Because of the large number of validation rules involved, using the policy pattern is very convenient. The code is as follows, the key is to understand the spirit, the implementation details do not elaborate ~~~

Var strategys = {isNotEmpty:function(value,errorMsg) {
        if(value === ' ') {
            returnerrorMsg; }}, // limit the minimum length minLength:function(value,length,errorMsg) {
        if(value.length < length) {
            returnerrorMsg; }}, // mobileFormat:function(value,errorMsg) {
        if(! /(^1[3|5|8][0-9]{9}$)/.test(value)) {returnerrorMsg; }}}; var Validator =function(){ this.cache = []; // save the rule}; 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);
                returnstrategys[strategy].apply(dom,strategyAry); }); })(rule); }}; Validator.prototype.start =function() {for(var i = 0, validatorFunc; validatorFunc = this.cache[i++]; ) { var msg = validatorFunc(); // Start the validation and get the return information after the validationif(msg) {
        returnmsg; }}}; Var registerForm = document.getelementById ("registerForm");
var validateFunc = function(){ var validator = new Validator(); / / create a Validator object / * add some efficacy rule * / Validator. Add (registerForm. UserName, [{strategy:'isNotEmpty',errorMsg:'User name cannot be empty'},
        {strategy: 'minLength:6',errorMsg:'Username length cannot be less than 6 characters'}]); validator.add(registerForm.password,[ {strategy:'minLength:6',errorMsg:'Password length must not be less than 6 characters'},]); validator.add(registerForm.phoneNumber,[ {strategy:'mobileFormat',errorMsg:'Mobile phone number format is not correct'},]); var errorMsg = validator.start(); // Get the effect resultreturnerrorMsg; }; // Click OK to submit registerForm.onSubmit =function(){
    var errorMsg = validateFunc();
    if(errorMsg){
        alert(errorMsg);
        return false; }}Copy the code