Strategy model of Java design pattern learning

Policy mode: policy mode is a method to define a series of algorithms. The work completed by the algorithms is the same, but the implementation is different. It can call all algorithms in the same way, reducing the coupling between various algorithm classes and using algorithm classes.

Java implements a policy pattern:

Demand: the cashier system of the shopping mall. The cashier mode is normal charging, 20% discount, and 100 back after 300. These three charging modes.

1: Create a superclass. That is, the abstract method of charging.

2: Create a class that implements this superclass.

3: According to the different charging methods of shopping malls, the specific implementation algorithm classes of three charging methods are created

4: Write a context to implement different payment methods through the same method. Because different objects need to be created, it needs to be implemented in combination with the simple factory pattern.

5: Test class

6: Console.

240.0 300.0 200.0

Summary: the policy pattern simplifies unit testing because each algorithm is its own class and can be tested separately through its own interface.

The policy pattern is used to encapsulate the algorithm, but in the actual use process, it can be used to encapsulate several rules of any type. As long as you hear that different business rules need to be applied at different times in the analysis process, you can consider the possibility of using the policy pattern to deal with this change.

My understanding: Generally speaking, the strategy mode encapsulates the algorithm, such as Kung Fu Panda. After inheriting the super class of animals, it needs to realize both the function of language and Kung Fu. Use the strategy mode to separate each algorithm and combine them well when used.

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
分享
二维码
< <上一篇
下一篇>>