The strategy pattern

The strategy pattern is to define a series of algorithms, encapsulate them one by one, and make them interchangeable.

The purpose of the policy pattern is to separate the use of the algorithm from the algorithm. The encapsulation algorithm is independent and does not change with the client.

Demo

We implement the addition, subtraction, multiplication and division of a counter to illustrate the policy pattern

function count(type, number1, number2) {
  switch (type) {
    case 'add':
      return number1 + number2;
    case 'subtract':
      return number1 - number2;
    case 'multiply':
      return number1 * number2;
    default:
      returnnumber1 / number2; }}// if else
function count1(type, number1, number2) {
  if (type === 'add') {
    return number1 + number2;
  } else if (type === 'subtract') {
    return number1 - number2;
  } else if (type === 'multiply') {
    return number1 * number2;
  } else {
    returnnumber1 / number2; }}Copy the code

Using the Policy Pattern

const count = {
  add(number1, number2) {
    return number1 + number2;
  },
  subtract(number1, number2) {
    return number1 - number2;
  },
  multiply(number1, number2) {
    return number1 * number2;
  },
  divide(number1, number2) {
    returnnumber1 / number2; }}; count.add(2.3); / / 5
count.subtract(10.3); / / 7
count.multiply(2.3); / / 6
count.divide(6.2); / / 3
Copy the code

scenario

The policy pattern is a common design pattern for example

  • Rules for form validation

  • The page needs to render different buttons for different conditions

  • The store calculates prices for different activities

  • .

advantages

  • Reducing duplicate code Strategy patterns reduce a lot of template code by using techniques and ideas such as composition, delegation, and polymorphism.

  • The extensibility policy pattern provides perfect support for the open-closed principle by encapsulating algorithms in separate policy classes, making them easy to switch, easy to understand, and easy to extend.