Three proxy patterns in Java

Time:2021-5-5

First: static proxy

code implementation

1. Design interface

public interface IUserDao {
    void save();
}

2. Implement the interface

public class UserDao implements IUserDao {

3. Agency The interface must be implemented

public class UserDaoProxy implements IUserDao {

4. Testing

public class App {

The second one is JDK dynamic proxy

code implementation

1. Design interface

public interface IUserDao {
    void save();
}

2. Implement the interface

public class UserDao implements IUserDao {

3. Agency There is no need to implement the interface

public class ProxyFactory {

4. Testing

public class App {

Third: cglib agent

code implementation

1. Target object class

public class UserDao {

2. Cglib agent factory

public class ProxyFactory implements MethodInterceptor {

3. Testing

public class App {

The difference between the three

1. Static agent

The target object needs to implement the interface, and the proxy object needs to implement the interface.

Such a proxy class can only proxy the objects of a specific interface, which is not flexible enough.

2. JDK dynamic proxy

The proxy object does not need to implement the interface, but the target object must implement the interface, otherwise dynamic proxy cannot be used

3. Cglib dynamic proxy

The proxy object does not need to implement the interface, and the target object can also be a simple object.

In AOP programming of spring:

If the target object added to the container has an implementation interface, use JDK proxy

If the target object does not implement the interface, use cglib proxy

This work adoptsCC agreementReprint must indicate the author and the link of this article