Detailed explanation of the strategy mode of Android design mode

Strategy mode

The effect of a function has different algorithms and strategies, and different results are selected according to different choices.

In short, as long as you have written a program, you have used the policy mode. Don't say you haven't used it. Haven't you used if else (switch)

In fact, if else is the embodiment of a policy pattern, which processes different results according to different choices.

problem

If you use if else (switch) to handle all the methods, it's OK in terms of function, but for the maintenance and use at the code level, more if else will make the class too large, unfavorable to read and difficult to modify

solve the problem

Use the policy pattern to define a unified interface. Each different function (if else) implements the interface as a specific class, and call the specific class externally to achieve different results.

Usage scenario

There are different solutions to the same problem. A class has multiple if else judgment processing results. When encapsulating the SDK, the caller cares about the results and does not pay attention to the implementation process. The animation timeinterpolator and listview adapter listed in the Android source code

code implementation

There is a commodity sale. In the process of sale, different prices (half price, 20% discount, 70% discount, etc.) should be given according to different users. On the premise of knowing the users, how can the price be given directly?

(1) Implementation of price interface

(2) Implement specific price classes

20% off:

50% off:

(3) Price algorithm management class

Pass in the specific implementation class and get the return interface

(4) Call mode

(5) Display results

Price after 50% discount for 1 yuan: 0.5 price after 70% discount for 2 yuan: 1.4

summary

For maintenance after using the policy mode, you only need to maintain the specific implementation class. If there is a new method, you only need to extend the implementation class to facilitate maintenance and use.

GitHub code address

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>