The meaning of a strategy pattern is to define a series of algorithms, encapsulate them one by one, and make them replaceable.
A small example can make us clear at a glance.
Recalling the animate method in jquery.
$( div ).animate( {"left: 200px"}, 1000, ‘linear' ); //Move at a constant speed
$( div ).animate( {"left: 200px"}, 1000, ‘cubic' ); //Cubic power temptation
These two codes make the div move 200 pixels to the right within 1000ms. Linear (constant speed) and cubic (clums power easing) are packages of a strategy mode.
Let’s take another example. I wrote in the first half of the year that many pages will have an instant verification form. Each member of the form will have some different verification rules.
For example, in the name box, it is necessary to verify the situations such as non-empty, sensitive words, and excessive characters. Of course, you can write 3 if else to solve the problem, but the scalability and maintenance of writing code in this way can be imagined. If there are more elements in the form and more cases that require verification, it is not impossible to write hundreds of if else in total.
So a better approach is to encapsulate each verification rule separately using a policy pattern. When you need to verify which type of verification, you only need to provide the name of this policy. Like this:
({
notNull: true,
dirtyWords: true,
maxLength: 30
})
NotNull, maxLength and other methods only need to return true or false uniformly to indicate whether they have passed the verification.
notNull: function( value ){
return value !== ”;
},
maxLength: function( value, maxLen ){
return () > maxLen;
}
}
As can be seen, various verification rules are easily modified and replaced with each other. If one day the product manager suggests that the limit for characters that are too long is changed to 60 characters. That only takes 0.5 seconds to complete the work.