Home >Web Front-end >JS Tutorial >Detailed explanation of the classic JavaScript design pattern Strategy Pattern
The meaning of strategy pattern is to define a series of algorithms, encapsulate them one by one, and make them interchangeable.
A small example can make it clear to us.
Recall the animate method in jquery.
$( p ).animate( {“left: 200px”}, 1000, ‘linear’ ); //匀速运动 $( p ).animate( {“left: 200px”}, 1000, ‘cubic’ ); //三次方的缓动
These two lines of code both make p move 200 pixels to the right within 1000ms. linear (uniform speed) and Cubic (cubic easing) is an encapsulation of the strategy pattern.
Let’s take another example. In the first half of the year I wrote dev.qplus.com, many pages will have an instant verification form. Each of the forms Members will have some different verification rules.
For example, in the name box, it needs to be verified that it is not empty, sensitive words, and characters are too long. Of course, you can write 3 if else to solve it, but the scalability and maintainability of writing code like this can be imagined. If there are more elements in the form and more situations need to be verified, it is not impossible to write hundreds of if elses in total.
So a better approach is to encapsulate each validation rule separately with a strategy pattern. When you need what kind of verification, you only need to provide the name of the policy. Like this:
nameInput.addValidata({ notNull: true, dirtyWords: true, maxLength: 30 }) 而notNull,maxLength等方法只需要统一的返回true或者false,来表示是否通过了验证。 validataList = { notNull: function( value ){ return value !== ”; }, maxLength: function( value, maxLen ){ return value.length() > maxLen; } }
As you can see, various validation rules can easily be modified and replaced with each other. If one day the product manager suggests that the character limit be changed to 60 characters. It only takes 0.5 seconds to complete the work.
Related articles:
JavaScript Design Pattern Classic Simple Factory Pattern Code Example
JavaScript Design Pattern Classic Singleton Pattern Detailed Explanation
Detailed introduction to the observer pattern of JavaScript design patterns
The above is the detailed content of Detailed explanation of the classic JavaScript design pattern Strategy Pattern. For more information, please follow other related articles on the PHP Chinese website!