SoFunction
Updated on 2025-04-07

JavaScript design pattern strategy pattern case sharing

Preface

The strategy design pattern refers to matching multiple solutions for a problem, not necessarily using one, and it is possible to add multiple solutions at any time.

For example, when we go to buy books, bookstores will hold some discount activities, 20 off for purchases over 100, 50 off for purchases over 200, and 20% off for purchases over 200, but there are more discounts in these places. Discount activities will be added one after another in the later stage, such as 30% off for the Double 11 event, and 30% off for the Double 11 event will be cancelled after the Double 11 event is over.

We do not use the strategy design model to calculate the discount price first. We declare a method, which accepts two parameters. One of these two parameters is the price and the other is the discount type. Then use the if statement in the method to determine the discount type to calculate the price. If there is no discount, it is the original price. Finally, the calculated discount price is returned.

//price price//type Discount Type function calcPrice(price, type) {
            if (type == '100_20') {
                price -= 20
            } else if (type == '200_50') {
                price -= 50
            }
            return price;

        }
        // use        const bookPrice = calcPrice(300, '100_20')

This method is OK if there are fewer discount activities, but every time you add a new discount activity, you need to add the if statement of the discount activity in the method and remember the fields of the new discount type to avoid duplication with the previous discount activity name. For the event that the discount activity expires, you need to manually delete the if statement. In the long run, the code is not only redundant but also very maintenance-oriented.

Implementation using policy design patterns:

We declare a closure function. There is a discount type center in the closure function, which contains several default discount types and a method to calculate the discount price. In terms of method, we have defined two methods for it, one is to add discount type methods, and the other is to delete discount type methods, and then expose the calculation discount method.

//Calculate the discount price closure function        const calcPrice = (function() {
            // Discount category center            const sale = {
           //100-20 Discount Event                    '100_20': function(price) {
                        return price -= 20
                    },
                    //200-50 Discount Event                    '200_50': function(price) {
                        return price -= 50
                    },
                    //A 20% discount event                    '80%': function(price) {
                        return price *= 0.8
                    },
                }
     
               /** *
                * Calculate the discount price
                * price
                * type Discount type
                * **/
            function totalPrice(price, type) {
                // Determine whether the discount type has this discount type. If there is one, execute it. If there is one, return to the original price if there is no one.                if (sale[type]) {
                    // Use discount function                    price = sale[type](price)
                }
                // Return to price                return price
            }
            /**
              *
              * Method of adding discounts
              * type Discount type
              * callback discount type method
              * **/
             = function(type, callback) {
                    // Determine whether the discount type exists                    if (sale[type]) return 'The discount already exists'
                    //Add discount price method to discount type center                    sale[type] = callback
                    return 'Discount method was added successfully'
                }
                // Method of deleting discounts                (type){
                //Delete discount type center method through delete keyword                   delete   sale[type] 
                }
             // The function returned is the ontology of calculating the price            return totalPrice
        })();
        // Use to calculate the price        const bookPrice = calcPrice(240, '200_50');
       //Add a 30% discount type method       ('70%',function(price) {return price *= 0.7 })
       //Delete the 20% discount type method        ('80%')

The strategy design pattern is easy to maintain, easy to understand and easy to expand

This is the article about sharing JavaScript design pattern strategy model case. For more related JavaScript strategy model content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!