The strategy pattern example _javascript skill of JavaScript design pattern

Source: Internet
Author: User

The meaning of a policy pattern is to define a series of algorithms, encapsulate them each, and make them interchangeable.
A small example will give us a clear glance.

Recall the Animate method in jquery.

Copy Code code as follows:

$ (div). Animate ({"left:200px"}, 1000, ' linear '); Motion
$ (div). Animate ({"left:200px"}, 1000, ' cubic '); Three-second side of the slow motion

The 2-sentence code is to have the div move 200 pixels to the right within 1000ms. Linear (constant) and cubic (three-second-order easing) are the encapsulation of a policy pattern.

One more example. I wrote the first half of the dev.qplus.com, many pages will have an instant verification of the form. Each member of the form has a different validation rule.

For example, the name box, you need to verify the non-empty, sensitive words, characters too long in these situations. Of course, you can write 3 if else to solve, but the extension and maintenance of this writing code is conceivable. If there are more elements in the form, there is a bit more to verify, and it is not impossible to add hundreds of if else.

So the better approach is to encapsulate each validation rule separately with the policy pattern. The name of the policy is only required when the validation is required. Just like this:

Copy Code code as follows:

Nameinput.addvalidata ({
Notnull:true,
Dirtywords:true,
Maxlength:30
})

Methods such as Notnull,maxlength only need to return true or false uniformly to indicate whether validation has been passed.
Copy Code code as follows:
Validatalist = {
Notnull:function (value) {
return value!== ";
},
Maxlength:function (value, MaxLen) {
return Value.length () > MaxLen;
}
}

As you can see, the various validation rules are easily modified and replaced by each other. If one day the Product manager recommends that the length of the characters be changed to 60 characters. It only takes 0.5 seconds to finish the work.

Related Article

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.