Before dealing with unknown things, we can have a variety of assumptions and generate different plans. We adopt the right plan for different situations, which is the strategic mode
- define
Define a set of algorithms, encapsulate them one by one, and make them interchangeable.
- The core
Separate the use of algorithms from the implementation of algorithms.
A policy-based program consists of at least two parts:
The first part is a set of policy classes, which encapsulate the specific algorithm and are responsible for the specific calculation process.
The second part is the Context class, which accepts a client’s request and then delegates it to a policy class. To do this, a reference to a policy object is maintained in the Context
- implementation
Policy patterns can be used to combine a series of algorithms as well as a series of business rules
In terms of composing business rules, the classic approach is form validation. Here are the key parts
Var errorMsgs = {default: "The input data format is incorrect ", minLength:" the input data length is insufficient ", isNumber: "Please input a number ", require: } function Validator() {this.rules = {minLength: function (v1, v2, errorMsg) { if (v1.length < v2) { return errorMsg || errorMsgs['minLength'] } }, isNumber: function (v1, v2, errorMsg) { if (! /\d+/.test(v1) && v2 == true) { return errorMsg || errorMsgs['isNumber']; } }, required: function (v1, v2, errorMsg) { if (v1 === '' && v2 === true) { return errorMsg || errorMsgs['required']; }}}}; Prototype = {constructor: Validator, // function (value, rules) { for (const rule of rules) { if (rule.isNumber ! == undefined) { let res = this.rules["isNumber"](value, rule.isNumber, rule.message) if (res) { return res } } if (rule.required ! == undefined) { let res = this.rules["required"](value, rule.required, rule.message) if (res) { return res } } if (rule.minLength) { let res = this.rules["minLength"](value, rule.minLength, rule.message) if (res) { return res } } } }, }; var validate = new Validator(); Console. log(validate.test(' CCC ', [{isNumber: true, message: "numbers only"}])); Console. log(validate.test('12', [{required: true, message: "cannot be null"}, {minLength: 5, message: "minimum 5 bits"}])); console.log(validate.test('123', [{ minLength: 5 }])); console.log(validate.test('12345', [{ minLength: 5 }]));Copy the code
source