Home >Web Front-end >JS Tutorial >Javascript Strategy Pattern
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
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
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('用户名长度不能小于6位'); return false; }else if(form.password.value.length <= 6){ alert('密码长度不能小于6位'); return false; }else if(!/(^1[3|5|8][0-9]{9}$)/.test(form.phone.value)){ alert("手机号码格式不正确"); return; }else{ submit(); } }
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 === '') { 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: 'isEmpty',errorMsg:'用户名不能为空'}, {strategy: 'minLength:6',errorMsg:'用户名长度不能小于6位'} ]); validator.addRule(form.password,[ {strategy: 'minLength:6',errorMsg:'密码长度不能小于6位'}, ]); validator.addRule(form.phone,[ {strategy: 'illegalPhone',errorMsg:'手机号格式不正确'}, ]); return validator.check(); }; form.onsubmit = function(){ let errorMsg = validateFunc(); if(errorMsg){ alert(errorMsg); return false; }else{ submit(); } }
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
The above is the detailed content of Javascript Strategy Pattern. For more information, please follow other related articles on the PHP Chinese website!