Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the policy mode in java

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces what is the strategic model in java, which has a certain reference value. Interested friends can refer to it. I hope you will gain a lot after reading this article.

What is a strategic model?

For example, a certain behavior of an object can be implemented differently in different scenarios, so that these implementations can be defined as a set of policies. Each implementation class corresponds to a policy, and different implementation classes are used in different scenarios. And you can switch policies freely.

The structure diagram of the policy pattern is as follows:

The policy pattern requires a policy interface, and different policies implement different implementation classes. Only the policy interface is held in the specific business environment, and different implementation classes can be used according to different scenarios.

Interface-oriented programming, not implementation-oriented.

Advantages of the policy model:

1. Get rid of the tedious if and switch judgment logic

2. The code is elegant, reusable and readable

3. In line with the principle of opening and closing, good expansibility and easy maintenance

Disadvantages of the policy model:

1. If there are many strategies, it will cause the expansion of policy classes.

2. Users must be aware of all policy classes and their uses

Strategy mode actual combat

To take a practical example, XX makes payments, and there are different payment methods and payment products according to different types of customers, such as credit cards and local payments, while local payments have WeChat Pay, Alipay, Cloud Flash, and other third-party payment companies in China, so the strategy model will come in handy.

The traditional if/ else/ switch and other judgment writing methods will be written by everyone, here will not paste the code, directly look at the strategy mode how to do!

1. Define policy interface

Define a policy interface, the interface for all payment methods.

Policy Interface:

/ * payment interface * @ author: stack length * @ from: official account Java technology stack * / public interface IPayment {/ * payment * @ param order * @ return * / PayResult pay (Order order);}

Order information class:

/ * * order information * @ author: stack length * @ from: official account Java technology stack * / @ Data public class Order {/ * * amount * / private int amount; / * * payment type * / private String paymentType;}

Return the result class:

/ * * @ author: stack length * @ from: official account Java technology stack * / @ Data @ AllArgsConstructor public class PayResult {/ * payment result * / private String result;} 2, define various policies

Define a variety of payment strategies, WeChat Pay, Alipay, Cloud Flash and other payment implementation classes all implement this interface.

WeChat Pay realized:

/ * * WeChat Pay * @ author: stack length * @ from: official account Java technology stack * / @ Service ("WechatPay") public class WechatPay implements IPayment {@ Override public PayResult pay (Order order) {return new PayResult ("WeChat Pay success");}}

Alipay realizes:

/ * * Alipay * @ author: stack length * @ from: official account Java technology stack * / @ Service ("Alipay") public class Alipay implements IPayment {@ Override public PayResult pay (Order order) {return new PayResult ("Alipay successful");}}

Cloud flash payment implementation:

/ * * UnionPay Cloud Flash pay * @ author: stack length * @ from: official account Java Technology Stack * / @ Service ("UnionPay") public class UnionPay implements IPayment {@ Override public PayResult pay (Order order) {return new PayResult ("Cloud Flash payment success");}}

Here, I use @ Service annotation to generate Bean for all payment methods and put them in the Spring Bean container. Instead of using new payment objects when using the strategy, we can directly use Bean, which is closer to the business. Spring basic tutorials will not be introduced, you can follow the official account Java technology stack, reply: spring, history tutorials have been sorted out.

3. Use strategy

Some articles use enumeration and HashMap to map the policy implementation class according to the policy name, which is no problem, but in the project that uses the Spring framework, it is still a bit superfluous. You can give full play to the advantages of the Spring framework and use the Bean name to find the corresponding policy implementation class.

The reference sample code is as follows:

/ * * payment service * @ author: stack length * @ from: official account Java technology stack * / @ RestController public class PayService {@ Autowired private ApplicationContext applicationContext / * payment interface * @ param amount * @ param paymentType * @ return * / @ RequestMapping ("/ pay") public PayResult pay (@ RequestParam ("amount") int amount, @ RequestParam ("paymentType") String paymentType) {Order order = new Order (); order.setAmount (amount); order.setPaymentType (paymentType) / / get the corresponding policy bean IPayment payment = applicationContext.getBean (order.getPaymentType (), IPayment.class) according to the payment type; / / start payment PayResult payResult = payment.pay (order); return payResult;}}

Look at the sample code, I did not create a new Context class holding policy interface as in the policy pattern structure diagram, that is the standard policy mode, in fact, the reason is the same, the key is how to implement the policy.

Test it:

Http://localhost:8080/pay?amount=8800&paymentType=WechatPay

When testing OK, different payment methods are passed in and different policies are called.

All the practical source code for this tutorial has been uploaded to this warehouse: https://github.com/javastacks/javastack

Application of Policy pattern in JDK

Now that we know how to use the policy pattern, let's take a look at where the policy pattern is used in JDK.

1. Reject policy in thread pool

There is a deny policy parameter in the construction of the thread pool, and the default is the default reject policy:

This is actually a policy interface:

There are several implementations of rejection policies:

Image-20210329161322406

When you create a thread pool, you can pass in different reject policies, which is the classic implementation of the policy pattern in JDK.

2. Comparator

Comparator is widely used as a policy interface in JDK:

There is a policy interface, but the policy needs to be determined by the developer.

Collection sorting is familiar to us, and different sorting rules are actually different strategies:

This policy pattern uses a functional programming interface, and comparison rules can be done using anonymous inner classes or Lambda expressions. There is no need for each rule to define an implementation class, thus omitting a large number of policy classes.

This strategy pattern may be hidden deeply, but it is also the application of the classic strategy pattern in JDK.

It's not limited to these two. There's actually more. Do you know anything else? Welcome to leave a message to share.

So, the strategy pattern is right around you, and you use it all the time, but you may not realize it.

Thank you for reading this article carefully. I hope the article "what is the strategic mode in java" shared by the editor will be helpful to you. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report