A deep understanding of the JavaScript series (33): detailed explanation of the Strategy Mode of the Design Mode
This article mainly introduces a deep understanding of the JavaScript series (33): detailed explanation of the policy pattern of the design pattern. The policy Pattern Defines the algorithm family and encapsulates them separately so that they can replace each other, this mode prevents algorithm changes from affecting customers who use the algorithm. For more information, see
Introduction
The rule mode defines the algorithm family and encapsulates them separately so that they can replace each other. This mode prevents algorithm changes from affecting the customers who use the algorithm.
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 add more requirements, we need to modify the code again to increase the logic, and the unit test will become more and more complex. The Code is as follows:
The Code is as follows:
Validator = {
Validate: function (value, type ){
Switch (type ){
Case 'isnonempty ':
{
Return true; // NonEmpty Verification Result
}
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:
The Code is as follows:
Var validator = {
// All the places where the validation rule processing class can be stored will be defined separately later
Types :{},
// Error message corresponding to the verification type
Messages: [],
// Of course, the authentication type is required
Config :{},
// Exposed public Verification Method
// 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]; // gets the verification class of the verification rule
If (! Type ){
Continue; // If the verification rule does not exist, it will not be 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:
The Code is as follows:
// 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:
The Code is 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 for obtaining the verification result is simple:
The Code is as follows:
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.