This content originally appeared on Level Up Coding - Medium and was authored by Maxwell

The purpose of learning design patterns is code reusability, to make code easier for others to understand, and to ensure code reliability. Design patterns make coding truly engineering; design patterns are the cornerstone of software engineering, like the structure of a building.
There are 23 classic design patterns, but not every design pattern is used frequently. Here, we introduce the most common and practical design patterns. In the last issue, we introduced the singleton pattern. Today, we will introduce the Strategy Pattern.
In computer programming, the strategy pattern (also known as the policy pattern) is a behavioral software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use.
If you are developing an online store project, each product has an original price, called originalPrice. But not all products are actually sold at full price, and promotions that allow items to be sold at a discount may be introduced.
Merchants can set different statuses for products in the background, and then the actual selling price will be dynamically adjusted according to the product status and original price.
The specific rules are as follows:
- Some products are pre-sold: To encourage customers to pre-order, there will be a 20% discount on the original price.
- Some products are in the normal promotion stage: if the original price is less than or equal to 100, they will be sold at a 10% discount; if the original price is higher than 100, they will be discounted by 10 yuan.
- Some products do not have any promotions: they are in default status and sold at full price.
At this time, you need to write a function getPrice to get the price of the product. How should you write it?
function getPrice(originalPrice,status){
//...
//return price
}In fact, in the face of such a problem, without considering any design patterns, the most intuitive way to write it may be if-else multiple conditional judgment statements to calculate the price.
There are three states, and you can quickly write code like this:
There are three conditions, the above code writes three if statements, which is very intuitive code, but this code is not well organized.
First, it violates the Single Responsibility Principle (which states that every class or function should have a single function, and that function should be fully encapsulated by this class or function). The function getPrice does too many things, this function is not easy to read and it is prone to bugs. If one condition bugs, the entire function crashes. At the same time, such code is not easy to debug.
And it is difficult for this code to cope with changing requirements. At this time, it is necessary to consider the design pattern, which often shows its charm when the business logic changes.
Assuming the business expands, there’s another discount sale right now: Black Friday. The discount rules are as follows:
- Products priced less than or equal to $100 are sold at a 20% discount.
- Products priced above $100 but below $200 will be discounted by $20.
- Products priced above or equal to $200 will be reduced by $20.
How to extend the getPrice function at this time?
It looks like you have to add a conditional statement to the getPrice function:
Whenever the discount is increased or decreased, the function needs to be changed. This practice violates the open-closed principle (open for extension, closed for modification). Modifying existing functionality is prone to new bugs and makes getPrice more and more bloated.
So how to optimize this code?
First, the function getPrice can be split to reduce bloat.
After this modification, although the number of lines of code has increased, the readability has been significantly improved. The getPrice function is obviously not so bloated, and it is more convenient to write unit tests.
But the above changes don’t solve the fundamental problem: the code is still full of if-else s, and getPrice still needs to be modified when adding or subtracting discount rules.
In fact, the purpose of using these if-else is to correspond to the status and discount strategy.

As can be seen from the figure, this logic is essentially a mapping relationship: the mapping relationship between product status and discount strategy.
Maps can be used instead of lengthy if-else to store maps. According to this idea, a price strategy mapping relationship (the mapping between strategy names and their processing functions) can be constructed, as follows:
Combining the state with the discount strategy, the price function can be optimized as follows:
At this time, if you need to add or subtract discount strategies, you do not need to modify the function, you only need to modify the price strategy mapping relationship priceStrategies
The previous code logic is as follows:

The optimized code logic is as follows:

The above optimization strategy uses the strategy pattern of the design pattern, which is more practical in the actual project development process.
Under what circumstances can you consider using the strategy pattern? If the function has the following characteristics:
- There are many judgment conditions
- The codes under each judgment condition are independent of each other.
Then the code under each judgment condition can be encapsulated into an independent function, and then the mapping relationship between the judgment condition and the specific strategy can be established.
JavaScript Design Patterns : Singleton Pattern
JavaScript Design Patterns: Strategy Pattern was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Level Up Coding - Medium and was authored by Maxwell
Maxwell | Sciencx (2022-10-25T02:50:45+00:00) JavaScript Design Patterns: Strategy Pattern. Retrieved from https://www.scien.cx/2022/10/25/javascript-design-patterns-strategy-pattern/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.