js Design Patterns - Strategy Pattern

Strategy Mode (Strategy)

Definition: The definition encapsulates a set of algorithms, it may be replaced with each other. Package algorithm has a certain independence, will not change with the client

Ado, let's example

// 例如要写一个计算两个数加减乘除的方法,会有人这么写
countNum(type, num1, num2) {
  if(type === 'add'){
    return num1 + num2
  } else if(type === 'subtract'){
    return num1 - num2
  } else if(type === 'multiply'){
    return num1 * num2
  } else {
    return num1 / num2
  }
}

countNum('add', 9, 3)       // 12
countNum('subtract', 9, 3)  // 6
countNum('multiply', 9, 3)  // 27
countNum('', 9, 3)          // 3

The above example, some people will be so written, you do not want to say I have no idea (~ ¯ ▽ ¯) ~, written first is not conducive to maintenance, in fact, is not good to facilitate expansion

Improve it:

let countNum = {
  add(num1, num2) {
    return num1 + num2
  },
  subtract(num1, num2) {
    return num1 - num2
  },
  multiply(num1, num2) {
    return num1 * num2
  },
  divide(num1, num2) {
    return num1 / num2
  },
}

countNum.add(9, 3)      // 12
countNum.subtract(9, 3) // 6
countNum.multiply(9, 3) // 27
countNum.divide(9, 3)   // 3

The above example can be seen as a strategy pattern

now, now there is a demand, about Christmas, so blanket, some products in supermarkets sell 20% off, 10% off the sale of a part of, wait until New Year's Day but also to engage in a major event, the average user full 100 back to 30, VIP user full 100 back to 50, with strategy model to achieve

// 定义一个策略对象
let priceceStrategy = function(){
  // 内部算法对象 
  let strategy = {
    return30(price){
      return price + parseInt(price / 100) * 30
    },
    return50(price){
      return price + parseInt(price / 100) * 50
    },
    price80(price){
      return price  * 80 / 100
    },
    price90(price){
      return price  * 90 / 100
    }
  }
  // 策略方法调用接口
  return {
    strategyFunction(type, price) {
      return strategy[type] && strategy[type](price)
    },
    // 添加算法
    addStrategy(type, fn){
      strategy[type] = fn
    }
  }
}()

priceceStrategy.strategyFunction('return30', 100)   // 130
priceceStrategy.strategyFunction('return50', 100)   // 150
priceceStrategy.strategyFunction('price80', 100)    // 80
priceceStrategy.strategyFunction('price90', 100)    // 90
// 添加一个算法
priceceStrategy.addStrategy('return70', (price) => {
  return price + parseInt(price / 100) * 70
})
console.log(priceceStrategy.strategyFunction('return70', 100))  // 170

And our form validation can also use the Strategy Pattern

// 定义一个策略对象
let inputStrategy = function(){
  // 内部算法对象 
  let strategy = {
    notNull(value){
      return /\s+/.test(value) ? '请输入内容' : ''
    },
    number(value){
      return /^[0-9]+(\.[0-9]+)?$/.test(value) ? '' : '请输入数字'
    }
  }
  // 策略方法调用接口
  return {
    check(type, value) {
      // 去除空白符
      value = value.replace(/^\s+|\s+$/g, '')
      return strategy[type] && strategy[type](value)
    },
    // 添加策略
    addStrategy(type, fn){
      strategy[type] = fn
    }
  }
}()

// 添加算法
inputStrategy.addStrategy('nickName', (value) => {
  return /^[a-zA-Z]\w{3,7}$/.test(value) ? '' : '请输入4-8为昵称'    
})

to sum up

Policy object behavioral pattern belongs mode mainly for a set of algorithms, each algorithm is encapsulated into a separate class have a common interface, so that that they can replace each other. Changes in the policy mode makes the algorithm can not affect the client's situation. Typically, the strategy pattern applies when an application needs to implement a specific service or function, and the program has a variety of implementations of the time.

Strategy mode of three objects:

  • Environmental objects : the class implements the interface or abstract class references to the abstract defined in the policy.
  • Abstract policy object : it can be an interface or abstract class to achieve.
  • Specific policy object : it encapsulates the different algorithms with no function.

Utilization Strategy mode to build applications based on user configuration, etc., have to select a different algorithm to achieve the functionality of the application. Specific environmental objects choose to complete. In this way the code to avoid the use of conditional statements brought confusion, improve flexibility and clarity of the application.

advantage:
  1. Multiple conditional optimization , using the strategy pattern algorithm is more conducive to safeguarding
  2. Scalability , strategy mode provides perfect support for the "opening and closing principle", the user can select on the basis of the algorithm or behavior does not modify the original system, but also the flexibility to add new algorithms or behavior.
  3. You can switch freely between policy class , due to the policy classes implement the same interface, so you can switch freely between them.
Disadvantages:
  1. Since the option to decide which algorithms in user, so the user must know the implementation of each algorithm.
  2. Because between each algorithm independent, so that for some complex algorithm processing part of the same logic can not be shared, some of which will result in waste of resources.

Guess you like

Origin www.cnblogs.com/loveyt/p/11057884.html