Home > Article > Web Front-end > JavaScript design pattern strategy pattern example_javascript skills
The meaning of the 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.
These two lines of code both make the div move 200 pixels to the right within 1000ms. Linear (uniform speed) and cubic (cubic easing) are encapsulation of a strategy pattern.
Let’s take another example. In the dev.qplus.com I wrote in the first half of the year, many pages will have instant verification forms. Each member of the form will have some different validation rules.
For example, in the name box, it needs to be verified that it is not empty, sensitive words, and the characters are too long. Of course, you can write three if elses to solve the problem, but the scalability and maintainability of writing code in this way 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 in the strategy pattern. When you need what kind of verification, you only need to provide the name of the policy. Like this:
As you can see, various validation rules can be easily 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.