JS Common design Pattern (9)--Strategy mode

Source: Internet
Author: User

The meaning of the strategy pattern is to define a series of algorithms, encapsulate them one by another, and make them interchangeable.
A small example can make us at a glance.

Recall the Animate method in jquery.

$ (div). Animate ({"left:200px"}, +, ' linear ');  //  $ (div). Animate ({"left:200px"}, +, ' cubic ');  // three-time side of the slow

All 2 lines of code let div move 200 pixels to the right within 1000ms. Linear (constant speed) and cubic (three-square easing) are the encapsulation of a strategy pattern.

One more example. In the first half of my dev.qplus.com, many pages will have an instant verification form. Each member of the form will have some different validation rules.

For example, in the Name box, you need to verify the non-empty, sensitive words, characters too long in several cases. Of course, you can write 3 if else to solve, but so the code extensibility and maintainability is conceivable. It is not impossible to add up hundreds if else if there are more elements in the form that need to be verified.

So a better approach is to encapsulate each validation rule in a separate policy pattern. You only need to provide the name of the policy when you need to verify it. Just like this:

Nameinput.addvalidata ({    true,    true,    += {    function (value) {      return value!== ';   }   ,function(value, MaxLen) {      return value.length () > maxlen;   

As you can see, various validation rules are easily modified and replaced with each other. If one day the Product manager recommends that the character be too long, the limit is changed to 60 characters. It only takes 0.5 seconds to finish the job.

JS Common design Pattern (9)--Strategy mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.