The definition of a policy pattern is to define a series of algorithms, seal them up and make them interchangeable.
JavaScript version of the policy mode:
Bonus system:
varStrategies = { "S":function(Salary) {returnSalary*4; }, "A":function(Salary) {returnSalary*3; }, "B":function(Salary) {returnSalary*2; } }; varCalculatebonus =function(level,salary) {returnStrategies[level] (salary); }; Console.log (Calculatebonus (' S ', 20000));//Output: 80000Console.log (Calculatebonus (' A ', 10000));//Output: 30000
To implement an easing animation using the policy mode:
<! DOCTYPE html>#div {position:absolute; Background:blue; width:50px; height:50px; } </style>varTween ={linear:function(t,b,c,d) {returnC*t/d+b;}, EaseIn:function(t,b,c,d) {returnc* (T/=d) *t+b;}, Strongeasein:function(t,b,c,d) {returnc* (T/=d) *t*t*t*t+b;}, Strongeaseout:function(t,b,c,d) {returnc* ((t=t/d-1) *t*t*t*t+1) +b;}, Sineasein:function(t,b,c,d) {returnc* (T/=d) *t*t+b;}, Sineaseout:function(t,b,c,d) {returnc* ((t=t/d-1) *t*t+1) +b; } }; varAnimate =function(DOM) { This. Dom = dom;//The DOM node that is moving This. startTime = 0;//Animation start Time This. startpos = 0; This. Endpos = 0; This. PropertyName =NULL; This. easing =NULL; This. Duration =NULL; }; Animate.prototype.start=function(propertyname,endpos,duration,easing) {//Start this animation This. StartTime = +NewDate; This. startpos = This. Dom.getboundingclientrect () [PropertyName];//Dom initial node location This. propertyname = PropertyName;//DOM node needs to be changed CSS property name This. Endpos = Endpos;//DOM node target location This. Duration = Duration;//Animated Continuous Events This. easing = tween[easing];//Easing algorithm varSelf = This; varTimeid = SetInterval (function(){ if(Self.step () = = =false) {clearinterval (Timeid); } },19) }; Animate.prototype.step=function(){//represent every frame of the ball movement to do varT = +NewDate; if(t>= This. starttime+ This. Duration) {//Fixed ball position This. Update ( This. Endpos);//Update the CSS property values for the ball return false; } varpos = This. Easing (t This. StartTime, This. Startpos, This. endpos- This. Startpos, This. Duration); This. Update (POS);//Update the CSS property values for the ball }; Animate.prototype.update=function(POS) { This. dom.style[ This. propertyname] = pos+ ' px '; }; vardiv = document.getElementById (' div '); varAnimate =NewAnimate (DIV); Animate.start (' Left ', 500,1000, ' strongeaseout '); //animate.start (' Top ', 1500,500, ' Strongeasein ');</script>
The policy pattern refers to defining a series of algorithms and encapsulating them.
Form validation:
Checksum logic:
- User name cannot be empty
- Password length cannot be less than 6 bits
- Mobile phone number must conform to format
<! DOCTYPE html>Please enter user name:<input type= "text" name= "UserName" >Please enter your password:<input type= "text" name= "password" >Please enter your mobile phone number:<input type= "text" name= "PhoneNumber" > <button> submit </button> </form></body>varStrategies ={isnonempty:function(value,errormsg) {//is not empty if(Value = = "){ returnerrormsg; }}, MinLength:function(value,length,errormsg) {//Limit Minimum Length if(Value.length <length) { returnerrormsg; }}, IsMobile:function(value,errormsg) {//mobile phone number format if(!/^1[3|5|8][0-9]{9}$/. Test (value)) { returnerrormsg; } } }; //Validator Implementation varValidator =function(){ This. cache = []; }; Validator.prototype.add=function(dom,rules) {varSelf = This; for(varI=0,rule;rule = rules[i++]; ){ (function(rule) {varStrategyary = Rule.strategy.split (': ')); varErrorMsg =rule.errormsg; Self.cache.push (function(){ varStrategy =Strategyary.shift (); Strategyary.unshift (Dom.value); Strategyary.push (ERRORMSG); returnstrategies[strategy].apply (dom,strategyary); }); }) (rule)}}; Validator.prototype.start=function(){ for(varI=0,validatafunc;validatafunc = This. cache[i++]; ){ varErrorMsg =Validatafunc (); if(errormsg) {returnerrormsg; } } }; //User Call Code varRegisterform = document.getElementById (' Registerform ')); varValidatafunc =function(){ varValidator =NewValidator ();//Create a Validator objectValidator.add (registerform.username,[{strategy:' Isnonempty ', ErrorMsg:' User name cannot be empty '},{Strategy:' Minlength:6 ', ErrorMsg:' User name length cannot be less than 6 bits ' }]); Validator.add (registerform.password,[{strategy:' Minlength:6 ', ErrorMsg:' Password length cannot be less than 6 bits ' }]); Validator.add (registerform.phonenumber,[{strategy:' IsMobile ', ErrorMsg:' Cell phone number format is incorrect ' }]); varErrorMsg =Validator.start (); returnerrormsg; }; Registerform.onsubmit=function(){ varErrorMsg =Validatafunc (); if(errormsg) {alert (errormsg); return false; } };</script>
Some advantages of the strategy mode:
The strategy mode can avoid multiple conditional selection statements effectively by using the techniques of combination, delegation and polymorphism.
The policy model provides perfect support for the open-closed principle, encapsulating the algorithms in separate startegy, making them easy to switch, easy to understand, and easy to extend.
Algorithms in the policy model can also be reused elsewhere in the system, avoiding many repetitive copy-pasting efforts.
Using composition and delegation in the policy model allows the context to have the ability to execute algorithms, which is a more portable alternative to inheritance.
In the JavaScript language strategy pattern, the policy class is often replaced by the function, at this time the strategy pattern is a kind of "invisible" pattern.
JavaScript Design patterns and development Practices---reading notes (5) Strategy mode