[Interview Question] How to understand the front-end design pattern-test strategy pattern?

Front-end interview question bank ( essential for interviews) Recommended: ★★★★★            

Address: Front-end interview question bank

[National Day Avatar] - National Day patriotic programmer avatar! always one option fit for you!

What is Strategy Pattern

Definition of Strategy pattern: This pattern defines a series of algorithms and encapsulates each algorithm so that they can be replaced with each other, and changes in the algorithm will not affect customers who use the algorithm.

problem to be solved

Suppose we need to write a function to calculate year-end bonus, our code may look like this

const bonus = function (level, salary) {
  if (level === "S") {
    return salary * 1.1;
  }
  if (level === "A") {
    return salary * 1;
  }
  if (level === "B") {
    return salary * 0.9;
  }
};

There are some problems with writing code like this:

  • If there are many situations, there will be a lot of judgment logic and the code will be messy.
  • It violates the closed development principle of design principles (open to expansion, closed to modification). To add logic, the original function must be modified.

We can optimize with the help of strategy pattern.

Single responsibility transformation

The return statement in each condition of the above code   is an algorithm . We can encapsulate each algorithm into a function.

      const levelS = (salary) => {
        return salary * 1.1;
      };
      const levelA = (salary) => {
        return salary * 1;
      };
      const levelB = (salary) => {
        return salary * 0.9;
      };
      const bonus = function (level, salary) {
        if (level === "S") {
          return levelS(salary);
        }
        if (level === "A") {
          return levelA(salary);
        }
        if (level === "B") {
          return levelB(salary);
        }
      };

After being encapsulated in this way, the algorithm for calculating the bonus for each win is separated separately to facilitate maintenance. But if there are other situations, we still have to write an if statement into the bonus function, and we need to continue optimizing

development closed renovation

  const levelObj = {
    S: (salary) => {
      return salary * 1.1;
    },
    A: (salary) => {
      return salary * 1;
    },
    B: (salary) => {
      return salary * 0.9;
    },
  };
  const bonus = function (level, salary) {
    return levelObj[level](salary);
  };

After this modification, if there is still D situation, we can modify it like this

levelObj.D = (salary)=> {
  return salary * 0.8;
},

It can be seen that the strategy pattern can better solve the loop nesting of if statements.

No matter how the logic in each of the above algorithms S, A, B, and D changes, it will not affect the core logic of the bonus. Therefore, we say: the strategy pattern defines a series they Interchangeable, and changes to the algorithm will not affect customers using the algorithm.

Use in vite configuration

Assume that our vite has three configuration files, a common viteBaseConfig configuration, a viteDevConfig configuration in dev mode, and a viteProdConfig configuration in production mode.

import { defineConfig } from "vite";
import viteBaseConfig from "./vite.base.config";
import viteDevConfig from "./vite.dev.config";
import viteProdConfig from "./vite.prod.config";
export default defineConfig(({ command, mode, ssrBuild }) => {
  if (command === "serve") {
    return {
      // dev 独有配置
      ...viteBaseConfig,
      ...viteProdConfig
    };
  } else {
    // command === 'build'
    return {
      // build 独有配置
      ...viteBaseConfig,
      ...viteDevConfig
    };
  }
});

The above code uses if statements to return different configuration items according to different modes. We can optimize them based on the knowledge we just learned.

Single responsibility transformation

//....
export default defineConfig(({ command, mode, ssrBuild }) => {
  const build = () => {
    // Object.assign中的{}是为了防止viteBaseConfig被修改。
    Object.assign({}, viteBaseConfig, viteProdConfig)
  },
  const serve = () => {
    // Object.assign中的{}是为了防止viteBaseConfig被修改。
    Object.assign({}, viteBaseConfig, viteDevConfig)
  },

  if (command === "serve") {
    return build()
  } else {
    // command === 'build'
    return serve();
  }
});

Object.assign()  The Object.assign() method copies all enumerable properties from one or more source objects to a target object, returning the modified object. Note: This method will modify the source object!

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);

console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }

console.log(returnedTarget === target);
// expected output: true

development closed renovation

const envResolver = {
  build: () => Object.assign({}, viteBaseConfig, viteProdConfig),
  serve: () => Object.assign({}, viteBaseConfig, viteDevConfig),
};
export default defineConfig(({ command, mode, ssrBuild }) => {
  return envResolver[command]();
});

 

 Front-end interview question bank ( essential for interviews) Recommended: ★★★★★            

Address: Front-end interview question bank

[National Day Avatar] - National Day patriotic programmer avatar! always one option fit for you!

Guess you like

Origin blog.csdn.net/weixin_42981560/article/details/132815771