preface
Strategy pattern is simply defined as a large family of algorithms, encapsulated separately, so that they can be interchangeable, algorithm changes will not affect the users of the algorithm
To put it simply, your girlfriend buys things on Taobao, there are many discount activities, such as full reduction, discount, 0 yuan purchase
In a normal implementation, that’s it
Oh, no. You don’t have a girlfriend
But! This doesn’t affect our understanding of the strategy pattern, so let’s move on
The strategic pattern is essentially designed to dispel the fear of Ifelse in the image above
Let’s try it out
To achieve the
Let’s start by defining a promotional interfacePromotionStrategy
Next three kinds of promotion strategy all to achieve this promotion interface, not a map
Let’s take FeeStrategy for $0 as an example
We could write another oneDefaultStrategyRun a default promotion when the promotional type is advertised externally
OK, now, before the container comes out, let’s take a look at our enumeration of promotional types
EnumPromotionType
We want to find a corresponding container-managed bean from the promotional type passed in. For example, 🌰, I’m currently passing in a 2-discount type, and I hope I can find the bean called DiscountStrategy
Let’s look at the code
OK, so we have our corresponding implementation class for the promotional type
Transform the pile of Ifelse at the beginning of the article
Now look, is not a lot of fresh
In the future, I need to increase strategic activities, such as buying a car for my girlfriend
Just add the enumeration class, and write another implementation class. No more Ifelse required
conclusion
- The strategic pattern is a well-understood design pattern that can be combined with a variety of design patterns, starting with our business scenarios
- By using the policy design pattern, the if statement in our method can be optimized away, which satisfies our open and closed principle and greatly increases our scalability
- So, I leave you with the question, which approaches in our framework use the policy pattern?
End of article 🤣
If this article has helped you, then give it a like
More sharing can be found on SKOW’s WeChat official account
Public number reply “information” can obtain big factory interview questions/technical documents/e-books and so on