Stop using a lot of if else, the code is too simple and the readability is too poor.
Definition of strategy pattern
....
Simple In other words, each module is independent of each other and does not affect each other to improve the scalability of the code!
For example, consider the following bad code
if ("花呗支付".equals(type)) { // 花呗支付的业务逻辑处理 } else if ("微信支付".equals(type)) { // 微信支付业务逻辑 } else if ("云闪付".equals(type)) { // 云闪付支付业务逻辑 } else if ("...".equals(type)) { // .... }
: You can define a payment interface, payment method, and different payments The method is to write different implementation classes without interfering with or affecting each other. If you add new payment methods in the future, you only need to add a new implementation class to implement the payment interface and rewrite its payment method without changing the code written before.
I happened to use this design pattern when I was typing code today. I would like to share it briefly.
Define the interface
Define different implementation classes
Each implementation class will handle its own business, do not interfere with each other, and are isolated from each other. For example, the following two implementation classes implement the same interface to handle different businesses
Define the interface
Isn’t it much simpler than a lot of if else~
Extract each different module, obtain the implementation class of the interface through the name of the bean, and execute the method
The above is the detailed content of How to use Java Strategy Pattern to replace if else. For more information, please follow other related articles on the PHP Chinese website!