Scenario: Travel to a certain place and choose the route according to the actual situation.

Solution:

  • If you can afford it, you can fly.
  • If the economy is similar, you can take the bus.
  • If you don’t have enough money, you can choose to ride a bike.

Strategy mode:

  • Concept: Define a set of algorithms and encapsulate them individually so that they are interchangeable.
  • Objective: To separate the use and implementation of algorithms.
  • Composition: A group of policy classes that encapsulate specific algorithms and are responsible for specific calculation procedures. An environment class that receives a customer’s request and then delegates the request to the environment class. (Key: indicates that the environment class must hold a reference to the policy class to implement the delegate.)

Application example: calculate year-end bonus

  • Year-end bonus: based on employees’ salary base and year-end performance.
    • Performance S: salary *4
    • Performance A: Salary *3
    • Performance B: Salary *2
  • Analysis: Find the invariable parts and the variable parts.
    • (1) Whether it is performance S, performance A or performance B, employees have corresponding performance. Therefore, from A wide range and generally speaking, employees have performance.
    • (2) Employees have their own wages, whether they are paid high or low.
    • (3) According to the first and second rules, employees are entitled to annual bonus regardless of whether the bonus is large or small. Therefore, the final result is: the constant total part is that everyone has annual bonus, i.e., everyone has annual bonus = performance * salary
    • (4) Variable part: Go into the specific performance of each person, everyone is different; Dive into the specifics of each person’s salary, everyone is different; Dive into the details of each person’s year-end bonus, everyone is different.
  • Understanding idea: extract the parts that are similar to everyone and isolate them separately, and then encapsulate the parts that are specific and different according to their own specific algorithms. (js in general is a function)

Code implementation

Use if conditional statement to realize year-end bonus calculation:

let getBonus=function(performance,salary){
  if(performance==='S') {return salary*4;
  }else if(performance==='A') {return salary*3;
  }else if(performance=='B') {return salary*2;
  }
}
const S_4000=getBonus('S', 4000); const S_5000=getBonus('S', 5000); const A_2000=getBonus('A', 2000); const A_3000=getBonus('A', 3000); console.log(S_4000,S_5000,A_2000,A_3000);Copy the code

Implement the strategy pattern in an object-oriented way:

class PerformanceS{
  getBonus(salary){
    return salary*4;
  }
}
class PerformanceA{
  getBonus(salary){
    return salary*3;
  }
}
class PerformanceB{
  getBonus(salary){
    return salary*2;
  }
}
class Bonus{
  constructor(){
    this.salary=null;
    this.strategy=null;
  }
  setSalary(salary){
    this.salary=salary;
  }
  setStrategy(strategy){
    this.strategy=strategy;
  }
  getBonus() {return this.strategy.getBonus(this.salary);
  }
}
const bonus=new Bonus();
const performanceS=new PerformanceS();
const performanceA=new PerformanceA();
bonus.setSalary(4000);
bonus.setStrategy(performanceS);
let bns=bonus.getBonus();
console.log(bonus);
Copy the code

Javascript implementation strategy pattern:

const strategies={
  "S":function(salary){return salary*4 },
  "A":function(salary){return salary*3},
  "B":function(salary){return salary*2}
};
const getBonus=function(strategy,salary){
  return strategies[strategy](salary);
};
Copy the code

Application Example: Form verification

<body>
<form id="registerForm">
    <input id="username"/>
    <input id="password"/>
    <input id="phoneNumber"/>
    <input type="submit"/>
  </form>
  <script src="./ form validation.js"></script>
</body>
Copy the code
/** * Policy mode: * Variable part: policy object, form validation has many different rules * constant part: */let strategy = {
  isNonEmpty: function (value, errorMsg) {
    if (value === ' ') {
      return errorMsg;
    }
  },
  minLength: function (value, length, errorMsg) {
    if (value.length < length) {
      return errorMsg;
    }
  },
  isMobile: function (value, errorMsg) {
    if(! /(^1[3|5|8][0-9]{9}$)/.test(value)) {returnerrorMsg; }}} // Get the form formlet registerForm = document.getElementById('registerForm'); /**registerForm.onsubmit <Function> * Task: When the submit button is clicked, the validation Function is started. If the errorMsg returned by the validation Function is not empty, the errorMsg is output and the form submission is blocked. */ registerForm.onsubmit =function () {
  let errorMsg = validaFunc();
  if (errorMsg) {
    alert(errorMsg);
    return false; // Block form submission}} /** Create a validator to add validation rules, start the validator, return the result of the validator errorMsg */let validataFunc = function () {
  let validator = new Validator();
  validator.add(registerForm.userName, 'isNonEmpty'.'User name cannot be empty');
  validator.add(registerForm.password, 'minLength:6'.'Password length must not be less than 6 characters');
  validator.add(registerForm.phoneNumber, 'isMobile'.'Incorrect format of mobile number');
  let errorMsg = validator.start();
  returnerrorMsg; }; /** *Validator <Constructor> * Role: Context * Function: receives user requests and delegates them to a Strategy object. * /let Validator = function() { this.cache = []; } /** prototype.add <Function> * DOM <Object> DOM node to which a rule needs to be added * rule <String> Name of the rule to be added * errorMsg <String> Verification error message */ validator.prototype. add =function (dom, rule, errorMsg) {
  let arr = rule.split(':'); // Separate strategy and parameters'isMobile:6'The result is the [strategy,6] /**validate <Function> * task: collect validation parameters, then call the policy object and pass in the parameters. * /let validate = function () {
    letstrategy = arr.shift(); // Get strategy arr.unshift(dom.value) from [strategy,6]; [dom.value,6] arr. Push (errorMsg); // Put the value of the form field into [6,]. [dom.value,6,errorMsg] [dom.value,6,errorMsg]returnstrategies[strategy].apply(dom, arr); } this.cache.push(validate); // Add the validation rule to the array}; / * * the Validator. Prototype. Start < XSL: > * task: cyclic Validator saved in the check rules, for each validation rules start check, calibration, however, and then if have return messages, is returned. * Self-perception: This function iterates through the cache properties (array) in the validator, and then calls each of the ValidatorFunc's in the array to get MSG (not null). It returns MSG * / Validator. Prototype. Start =function () {
  for (let i = 0; ValidatorFunc; ValidatorFunc = this.cache[i++]) {
    letmsg = ValidatorFunc(); // Start the validation and get the message returned by the validationif(MSG) {// If this message exists, there must be no validationreturnmsg; }}}Copy the code

About the author: Serics, Reeds Technology, Web front-end development engineer, good at website construction, wechat public account development, wechat small program development, small game production, enterprise wechat production, H5 construction, focus on front-end framework, server rendering, SEO technology, interaction design, image rendering, data analysis and other research.

Join us: [email protected] visit www.talkmoney.cn to learn more

Provide Shenzhen wechat public number production, high-quality nail nail outsourcing, Guangdong enterprise wechat construction, Dongguan wechat small program production, professional small game development, Guangzhou H5 construction