A deep understanding of the JavaScript series (33): The Strategic Pattern of the design pattern, and a deep understanding of javascript
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:
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:
Var validator = {// all the places where the verification rule processing class can be stored, and types :{} will be defined separately later. // the error message messages corresponding to the verification type: [], // Of course, the verification type config: {}, // exposed public verification method // The input parameter is 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 checker = this based on the key. types [type]; // obtain 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, throw an exception throw {name: "ValidationError", message: "No handler to validate type" + type };} result_ OK = checker. validate (data [I]); // verify 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 whether the given 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 digit 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 whether the given value is only a letter or number validator. types. isAlphaNum = {validate: function (value) {return! /[^ A-z0-9]/I. test (value) ;}, instructions ctions: "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:
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:
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.
Copyright statement: This article is the original author of the http://www.zuiniusn.com, not allowed by the blogger can not be reproduced.