Strategy + IOC destroy ifelse, bring it

Time:2021-8-15

preface

Strategy modeIn short, it defines a large family of algorithms and encapsulates them separately so that they can replace each other. The change of the algorithm will not affect the users using the algorithm

In short, your girlfriend 618 buys things on Taobao. There are many discount activities, such as full discount, discount and 0 yuan purchase

Common implementation, that’s it
Strategy + IOC destroy ifelse, bring it

Oh, no, you don’t have a girlfriend

But! This does not affect our understanding of the strategic model, we continue

Strategy + IOC destroy ifelse, bring it

The essence of the strategy model is to eliminate the fear brought by ifelse in the figure above

Now let’s practice

Realize it

Let’s define a promotion interface firstPromotionStrategy
Strategy + IOC destroy ifelse, bring it

The next three promotion strategies all implement this promotion interface, not one by one

We bought it for 0 yuanFeeStrategygive an example

Strategy + IOC destroy ifelse, bring it

We can also write oneDefaultStrategyA default promotion activity is carried out when the promotion type is blindly transmitted externally
Strategy + IOC destroy ifelse, bring it

OK, next, before the container comes out, let’s take a look at our enumeration of promotion types
EnumPromotionType
Strategy + IOC destroy ifelse, bring it

We hope to find the corresponding bean for container management through the promotion type passed in. For example, I hope I can find the 2-discount type I currently pass inDisCountStrategyThis bean

Come on, look at the code

Strategy + IOC destroy ifelse, bring it

OK, so we get the implementation class of our corresponding promotion type

Transform the pile of ifelse at the beginning of the article

Strategy + IOC destroy ifelse, bring it

Now it looks, isn’t it much refreshing

Strategy + IOC destroy ifelse, bring it

In the future, we need to increase strategic activities, such as buying a car to give away a girlfriend

Just add enumeration classes and write an implementation class. No more ifelse

summary

  • Policy pattern is a design pattern that is easy to understand. It can be combined with a variety of design patterns. Of course, the first starting point is our business scenario
  • Through the of the strategy design pattern, we can optimize the if statements in our method, meet our opening and closing principles, and greatly increase our scalability
  • So, let’s leave you a question. Which methods in our framework use the strategy pattern?

End of article

If this article is helpful to you, please praise it

More WeChat official account sharing Skow

Official account reply to “data” can get big factory interview questions / technical documents / e-books, etc.

Strategy + IOC destroy ifelse, bring it