foreword
The strategy design pattern refers to a problem that matches multiple solutions, which one is not necessarily used, and it is possible to add multiple solutions at any time
For example, when we go to buy books, the bookstore will hold some promotional activities, such as 20 off 100, 50 off 200, 20% off, etc., but there are more than these promotions, and promotions will be added in the future, such as 30% off on Double 11. After the double 11 event is over, the 30% discount event needs to be cancelled.
First, we don't use the strategy design pattern to implement the calculation of the discounted price. We declare a method that 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 and calculate the price. If If there is no discount, it is the original price, and finally return the calculated discount price
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
This method is okay if there are relatively few discount activities, but every time you add a new discount activity, you need to add the if statement of the discount activity to the method to judge and remember the field of the new discount type to avoid the previous discount activity. The name is repeated, and the if statement needs to be manually deleted when the discount activity expires. In the long run, the code is not only redundant but also very maintainable
Implemented using the strategy design pattern:
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 the method, we define two methods for him, one is to add The discount type method, one is to delete the discount type method, and then expose the calculation discount method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
|
The strategy design pattern is easy to maintain, easy to understand, and easy to expand