Home > Web Front-end > JS Tutorial > body text

Javascript Strategy Pattern

php中世界最好的语言
Release: 2018-03-13 17:44:11
Original
1612 people have browsed it

This time I bring you Strategy Mode of Javascript, what are the Notes of Javascript Strategy Mode, the following is a practical case, let’s take a look .

The strategy pattern refers to defining a series of algorithms and encapsulating each algorithm so that they can be replaced with each other. The Strategy pattern allows the algorithm to change independently of the clients using it.

The strategy pattern uses technologies and ideas such as combination and delegation to avoid many if conditional statements

The strategy pattern provides an open-closed principle, making the code easier to understand and expand

Simple value

Many examples, using performance grade and salary to calculate bonuses as examples

let calculateBouns = (level,salary)=>{    if(level=='A'){        return salary * 1.4;
    }else if(level=='B'){        return salary * 1.3;
    }else if(level=='C'){        return salary * 1.2;
    }else{        return salary;
    }
}console.log(calculateBouns('A', 8000)); //11200console.log(calculateBouns('C', 8000)); //9600
Copy after login

Strategy mode reconstruction

//策略对象class ruleA{    calculate(salary){        return salary * 1.4;    }} class ruleB{    calculate(salary){        return salary * 1.3;    }} class ruleC{    calculate(salary){        return salary * 1.2;    }} //奖金类class Bouns{    constructor(){        this.salary = null;        this.level = null;    }    setLevel(level){        this.level = level;    }    setSalary(salary){        this.salary = salary;    }    getBouns(){        return this.level.calculate(this.salary);    }}let tom = new Bouns(),jerry = new Bouns();//设置薪资tom.setSalary(8000);jerry.setSalary(10000);//设置策略对象tom.setLevel(new ruleA());jerry.setLevel(new ruleA());console.log(tom.getBouns()); //11200console.log(jerry.getBouns()); //14000jerry.setLevel(new ruleB());console.log(jerry.getBouns()); //13000
Copy after login

Form

Another example of understanding the strategy pattern is Form validation, which usually involves multiple field validity judgments

let form = document.getElementById("Form");
form.onsubmit = function(){    if(form.username.value == ''){
        alert('用户名不能为空');        return false;
    }else if(form.username.value.length <= 6){
        alert(&#39;用户名长度不能小于6位&#39;);        return false;
    }else if(form.password.value.length <= 6){
        alert(&#39;密码长度不能小于6位&#39;);        return false;
    }else if(!/(^1[3|5|8][0-9]{9}$)/.test(form.phone.value)){
        alert("手机号码格式不正确");        return;
    }else{
        submit();
    }
}
Copy after login

Disadvantages of the code implemented in this way:

The function is bloated and contains a lot of if judgments

The function lacks flexibility and violates the open-closed principle

The function has poor reusability. If you add a form that requires similar verification, you can only copy it once

Strategy pattern implements form validation

// 策略对象let strategys = {    isEmpty: (value,errorMsg)=> {        if(value === &#39;&#39;) {            return errorMsg;
        }
    },    // 限制最小长度
    minLength: (value,length,errorMsg)=> {        if(value.length < length) {            return errorMsg;
        }
    },    // 手机号码格式
    illegalPhone: (value,errorMsg)=> {        if(!/(^1[3|5|8][0-9]{9}$)/.test(value)) {            return errorMsg;
        }
    } 
};class Validator{    constructor(){        this.cache = []; //保存校验规则
    }
    addRule(dom,rules){        var self = this;        for(let i = 0, rule; rule = rules[i++]; ){            let strategyAry = rule.strategy.split(":");            let errorMsg = rule.errorMsg;
            self.cache.push(function(){                let strategy = strategyAry.shift();
                strategyAry.unshift(dom.value);
                strategyAry.push(errorMsg);                return strategys[strategy].apply(dom,strategyAry);
            });
        }
    }
    check(){        for(let i = 0, fn; fn = this.cache[i++]; ) {            let msg = fn(); // 开始效验 并取得效验后的返回信息
            if(msg) {                return msg;
            }
        }
    }
}// 代码调用let form = document.getElementById("Form");let validateFunc = function(){    let validator = new Validator(); // 实例化Validator
    //添加一些校验规则
    validator.addRule(form.username,[
        {strategy: &#39;isEmpty&#39;,errorMsg:&#39;用户名不能为空&#39;},
        {strategy: &#39;minLength:6&#39;,errorMsg:&#39;用户名长度不能小于6位&#39;}
    ]);
    validator.addRule(form.password,[
        {strategy: &#39;minLength:6&#39;,errorMsg:&#39;密码长度不能小于6位&#39;},
    ]);
    validator.addRule(form.phone,[
        {strategy: &#39;illegalPhone&#39;,errorMsg:&#39;手机号格式不正确&#39;},
    ]);    return  validator.check();
};
form.onsubmit = function(){    let errorMsg = validateFunc();    if(errorMsg){
        alert(errorMsg);        return false;
    }else{
        submit();
    }
}
Copy after login

The strategy pattern belongs to the object behavior pattern. It mainly targets a set of algorithms and encapsulates each algorithm into an independent class with a common interface so that they can interact with each other. replace.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of JS inheritance

Node file batch renaming

The above is the detailed content of Javascript Strategy Pattern. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template