Deep understanding of the JavaScript series (33): A detailed explanation of the strategic pattern of design Patterns _ basics

Source: Internet
Author: User

Introduced

The policy pattern defines the algorithm family, which is packaged so that they can be replaced by each other, and this pattern allows the algorithm to change without affecting the client using the algorithm.

Body

Before we understand the strategy model, let's start with an example, in general, if we want to do data validation of legality, often in accordance with the Swith statement to judge, but this brings a few problems, first of all, if we increase the demand, we have to modify this code again to increase the logic, And when it comes to unit testing, it's getting more complex, and the code is as follows:

Copy Code code as follows:

Validator = {
Validate:function (value, type) {
Switch (type) {
Case ' Isnonempty ':
{
return true; nonempty validation Results
}
Case ' Isnumber ':
{
return true; Number validation Results
Break
}
Case ' Isalphanum ':
{
return true; Alphanum Validation Results
}
Default
{
return true;
}
}
}
};
Test
Alert (Validator.validate ("123", "Isnonempty"));

So how to avoid the problem in the above code, according to the policy pattern, we can separate the same work code into different classes, and then through a unified policy processing class to deal with, OK, we first define the policy processing class, the code is as follows:
Copy Code code as follows:

var validator = {

All the validation rules that can be handled by the class are stored in a separate definition
Types: {},

Verify that the error message for the type corresponds to
Messages: [],

Of course the type of validation you need to use
Config: {},

Public authentication method of exposure
The arguments passed in are key => value pairs
Validate:function (data) {

var i, MSG, type, checker, RESULT_OK;

Clear all error messages
This.messages = [];

For (i in data) {
if (Data.hasownproperty (i)) {

Type = This.config[i]; Validation rules based on whether a key query exists
Checker = This.types[type]; Getting validation classes for validation rules

if (!type) {
Continue If the validation rule does not exist, it is not processed
}
if (!checker) {//If the validation rule class does not exist, throws an exception
throw {
Name: "ValidationError",
Message: ' No handler to validate type ' + type
};
}

                RESULT_OK = Checker.validate (Data[i]); Verify using a single validation class that is found
                 if (!RESULT_OK) {
                     msg = "Invalid value for *" + i + "*," + checker.instructions;
                     This.messages.push (msg);
               }
           }
       }
        return this.haserrors ();
   },

Helper
Haserrors:function () {
return this.messages.length!== 0;
}
};


The rest of the work, then, is to define the various validation classes stored in the types, and here are just a few examples:
Copy Code code as follows:

Verifies that a given value is not empty
Validator.types.isNonEmpty = {
Validate:function (value) {
return value!== "";
},
Instructions: "The value passed in cannot be null"
};

Verifies that a given value is a number
Validator.types.isNumber = {
Validate:function (value) {
return!isnan (value);
},
Instructions: "The passed-in value can only be a valid number, for example: 1, 3.14 or 2010"
};

Verifies whether a given value is just a letter or a number
Validator.types.isAlphaNum = {
Validate:function (value) {
return!/[^a-z0-9]/i.test (value);
},
Instructions: "The values passed in can only protect letters and numbers and cannot contain special characters"
};


When used, we first define the data set that needs to be validated, and then we need to define the type of rule that each data needs to be validated, as follows:
Copy Code code as follows:

var data = {
First_Name: "Tom",
Last_Name: "Xu",
Age: "Unknown",
Username: "Tomxu"
};

Validator.config = {
First_Name: ' Isnonempty ',
Age: ' Isnumber ',
Username: ' Isalphanum '
};


Finally, the code to get the results of the validation is simple:
Copy Code code as follows:

Validator.validate (data);

if (Validator.haserrors ()) {
Console.log (Validator.messages.join ("\ n"));
}


Summary

The policy pattern defines a series of algorithms, conceptually, that all of these algorithms do the same thing, only to implement it differently, that he can invoke all the methods in the same way, reducing the coupling between the various algorithmic classes and the use of algorithmic classes.

On the other hand, defining an algorithm class separately also facilitates unit testing, because it can be tested individually with its own algorithm.

In practice, not only can encapsulation algorithms, but also can be used to encapsulate almost any type of rules, is to be in the analysis process to apply different business rules at different times, you can consider the policy model to deal with a variety of changes.

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.