Today we are going to learn the common design pattern of JavaScript-- the strategy pattern definition defines a series of algorithms, encapsulating them individually, and making them interchangeable. extract and encapsulate seemingly unrelated code to make it easier to understand and expand. Let's understand it through an example: Application scenario there are different strategies to accomplish several things. For example, performance calculation, form validation rules calculate the year-end bonus after performance appraisal. S performance is four months' salary, A performance is three months' salary, B performance is two months' salary before use define a function to calculate bonus calculateBonus . The input parameters of the function are performance level and monthly salary function calculateBonus(level, salary) { switch (level) { case "s": { return salary * 4; } case "a": { return salary * 3; } case "b": { return salary * 2; } default: { return 0; } } }; calculate bonus calculateBonus('s', 10000); // 40000 calculateBonus('a', 5000); // 15000 if we want to modify the performance rules, we need to change the logic in the calculateBonus function, which violates the open and closed principle, so we can consider using the policy mode at this time. improve decouple all the logic function getS(salary){ return salary * 4 } function getA(salary){ return salary * 3 } function getB(salary){ return salary * 2 } function calculateBonus(level, salary) { switch (level) { case "s": { return getS(salary); } case "a": { return getA(salary); } case "b": { return getB(salary);; } default: { return 0; } } }; this is still a lot of…

June 13, 2023 0comments 1210hotness 0likes Aaron Read all