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.