A deep understanding of the Javascript series (33): The Strategic Pattern of the Design Pattern

Source: Internet
Author: User
Introduction

Policy mode definedAlgorithmFamily, respectively encapsulated, so that they can replace each other. This pattern prevents algorithm changes from affecting customers who use algorithms.

Body

Before understanding the rule mode, let's take an example. Generally, if we want to verify the validity of data, we usually judge the validity of the data according to the swith statement, but this raises several problems, first, if you want to increase the number of requests, we need to modify this section again.CodeTo increase the logic, and the unit test will become more and more complex, the Code is as follows:

Validator = {
Validate: Function (Value, type ){
Switch (Type ){
Case 'Isnonempty ':
{
Return True ; // Nonempty verification results
}
Case 'Isnumber ':
{
Return True ; // Number Verification Result
Break ;
}
Case 'Isalphanum ':
{
Return True ; // Alphanum Verification Result
}
Default :
{
Return True ;
}
}
}
};
// Test
Alert (validator. Validate ("123", "isnonempty "));

So how can we avoid problems in the above Code? According to the policy mode, we can encapsulate the same working code into different classes separately, and then process them through a unified policy processing class. OK, let's first define the Policy Processing class. The Code is as follows:

 VaR Validator = {

// All possible locations where the verification rule processing class is stored will be defined separately later
Types :{},

// Error message corresponding to the verification type
Messages: [],

// Of course, the authentication type to be used
Config :{},

// Exposed public verification methods
// The input parameter is a key => value pair.
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]; // Check whether there are validation rules based on the key
Checker = This . Types [type]; // Obtain the verification class of the verification rule

If (! Type ){
Continue ; // If the verification rule does not exist, it is not processed.
}
If (! Checker ){ // If the validation rule class does not exist, an exception is thrown.
Throw {
Name: "validationerror ",
Message: "No handler to validate type" + Type
};
}

Result_ OK = checker. Validate (data [I]); // Use a single verification class found for verification
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 is to define the various verification classes stored in types. Here we only give a few examples:

 //  Verify that the specified value is not empty  
Validator. types. isnonempty = {
Validate: Function (Value ){
Return Value! = "";
},
Instructions: "The input value cannot be blank"
};

// Verify whether the given value is a number
Validator. types. isnumber = {
Validate: Function (Value ){
Return ! Isnan (value );
},
Instructions: "The input value can only be a valid number, for example, 1, 3.14 or 2010"
};

// Verify that the given value is only a letter or number
Validator. types. isalphanum = {
Validate: Function (Value ){
Return ! /[^ A-z0-9]/I. Test (value );
},
Instructions: "Incoming values can only protect letters and numbers and cannot contain special characters"
};

When using this function, we first need to define the data set to be verified, and then define the rule types to be verified for each type of data. The Code is as follows:

 
VaRData = {
First_name: "Tom ",
Last_name: "Xu ",
Age: "unknown ",
Username: "tomxu"
};

Validator. Config = {
First_name: 'isnonempty ',
Age: 'isnumber ',
Username: 'isalphanum'
};

Finally, the Code for obtaining the verification result is simple:

 
Validator. Validate (data );

If(Validator. haserrors ()){
Console. Log (validator. Messages. Join ("\ n "));
}

Summary

Policy mode defines a series of algorithms. In terms of concept, all these algorithms do the same thing, but they implement different things. They can call all methods in the same way, reduces the coupling between various algorithm classes and algorithm classes.

In another aspect, it is convenient to define an algorithm class separately for unit testing, because you can perform separate tests using your own algorithms.

In practice, not only algorithms can be encapsulated, but almost any type of rules can be encapsulated. Different business rules must be applied at different times during the analysis process, it can be considered that the policy mode should be used to handle various changes.

 

Transferred from: Uncle Tom

 

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.