preface

I did a bookkeeping function earlier. The idea is that the behavior of different investors can have different effects on the accounts. For example, the investor bought a current product, money how to change. If investor buys fixed product, money wants again how how change. Blah, blah, blah, blah, blah, blah, blah.

So since we’ve seen a little bit about the strategy pattern, which is the behavior of an object, there are different algorithms for implementing it in different scenarios. One advantage of using the policy pattern is that each strategy is isolated from each other.

I was wondering if I could use it. If every action produces a change in money, these actions can be isolated, which should be very good. So I just think of money as an object, and money changes in different behaviors with different algorithms.

practice

Define the policies as follows and create them directly with @Component.

Then use @Autowire annotations where needed and call the corresponding policy method.

So far, that’s not bad. Encountered twice money calculation error bug, can also be relatively fast positioning. There is a new feature that reuses two of these policies directly.

To conclude, let’s look at the definition of the policy pattern.

The strategy pattern

A policy pattern is a behavior of an object that is implemented by different algorithms in different scenarios. For example, everyone has to pay personal income tax, so paying personal income tax in the US is not the same as paying personal income tax in China.

So, how to do that? Here’s a picture from the Internet:

Analyze the implementation of the strategy mode, in fact, that is, different algorithms have a common parent class, so the client when calling, just a new algorithm they want.

Therefore, corresponding to their own use, in fact, in Spring, each policy is first created, managed by Spring, when the client needs to call, can be introduced.

The above is my understanding of the strategic pattern. If you have any mistakes, please post them on Github. Thank you.

0    0