JavaScript: Rule mode of Design Pattern

Source: Internet
Author: User

JavaScript: Rule mode of Design Pattern
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 number validator. types. isNumber = {validate: function (value) {return! IsNaN (value) ;}, instructions: The passed 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: the incoming value 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());}
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.

 

Related Article

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.