Home >Web Front-end >JS Tutorial >JavaScript design pattern strategy pattern example_javascript skills

JavaScript design pattern strategy pattern example_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:34:231319browse

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.

Copy code The code is as follows:

$( div ).animate( {“left: 200px”}, 1000, ‘linear’ ); // Uniform motion
$( div ).animate( {“left: 200px”}, 1000, ‘cubic’ ); // Cubic easing

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:

Copy code The code is as follows:

nameInput.addValidata({
notNull: true,
dirtyWords: true,
maxLength: 30
})

The notNull, maxLength and other methods only need to uniformly return true or false to indicate whether the verification has passed.
Copy code The code is as follows:
validataList = {
notNull: function( value ){
return value !== ”;
},
maxLength: function( value, maxLen ){
return value.length() > maxLen;
}
}

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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn