JDK proxy-static proxy, dynamic proxy combat

When it comes to agents, we all know that agents are divided into static agents and dynamic agents.

Static proxy

  • Advantages: simple code structure, easier to implement

  • Disadvantages: unable to adapt to all agent scenarios. If there are new requirements, the agent class needs to be modified, which does not meet the opening and closing principles of software engineering

For static proxy, let's take the actual scene of life as an example. Below we upload the code:

//销售化妆品接口public interface Cosmetic {
   
       void sellCosmetic(double price);}//化妆品供货商public class CosmeticFactory implements Cosmetic {
   
       @Override    public void sellCosmetic(double price) {
   
           System.out.println("销售化妆品,价格为"+price);    }}//化妆品代理商(赚差价)public class CosmeticProxy implements Cosmetic {
   
       private CosmeticFactory factory;    public CosmeticProxy(CosmeticFactory factory){
   
           this.factory = factory;    }    @Override    public void sellCosmetic(double price) {
   
           doBeforeSell();        factory.sellCosmetic(price);        doAfterSell();    }    private void doBeforeSell() {
   
           System.out.println("代理购买化妆品前置操作...");    }    private void doAfterSell() {
   
           System.out.println("代理购买化妆品后置操作...");    }}//public class ProxyTest {
   
       public static void main(String[] args) {
   
           CosmeticFactory cosmeticFactory = new CosmeticFactory();        CosmeticProxy cosmeticProxy = new CosmeticProxy(cosmeticFactory);        cosmeticProxy.sellCosmetic(8888);     }}

We can see that implementing the proxy mode requires several steps:

  • Define the public interface of real objects and proxy objects (Cosmetic)

  • Reference to the real target object within the proxy object (reference supplier CosmeticFactory)

  • Access the real target object through the proxy object , not directly access the target object

Why is there a proxy object?

Purpose :

  • Through the isolation of proxy objects, additional business logic can be added before and after the access to the target object to achieve functional enhancement.

  • Accessing the target object through the proxy object can prevent the system from directly accessing the target object incorrectly in large numbers, resulting in unpredictable consequences

With a static proxy, why is there a dynamic proxy ?

The dynamic agent is improved on the basis of the static agent, which improves the maintainability and scalability of the program

Dynamic proxy

  • Advantages: It can dynamically adapt to specific agent scenarios, has good scalability, and conforms to the opening and closing principles of software engineering

  • Disadvantages: The dynamic proxy needs to use the reflection mechanism and dynamically generate bytecode, resulting in its performance is slightly worse than the static proxy, but compared to the advantages, the disadvantages are almost negligible

Directly on the code below:

//动态代理实现InvocationHandler,并实现其invoke()方法public class DynamicProxy implements InvocationHandler {
   
       private Object realObject;    public DynamicProxy(Object realObject){
   
           this.realObject = realObject;    }    @Override    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
   
           doBefore();        Object obj = method.invoke(proxy, args);        doAfter();        return obj;    }    private void doBefore() {
   
           System.out.println("动态代理代理前置操作...");    }    private void doAfter() {
   
           System.out.println("动态代理后置操作...");    }}public class ProxyTest {
   
       public static void main(String[] args) {
   
           CosmeticFactory cosmeticFactory = new CosmeticFactory();        DynamicProxy dynamicProxy = new DynamicProxy(cosmeticFactory);        Cosmetic cosmetic = (Cosmetic) Proxy.newProxyInstance(                        cosmeticFactory.getClass().getClassLoader(),                        cosmeticFactory.getClass().getInterfaces(),                        dynamicProxy);        cosmetic.sellCosmetic(9999);     }}

From the code, we can see that the invoke() method of InvocationHandler has 3a parameter:

  • Object proxy: Proxy object

  • Method method: The method of real execution

  • Object[] agrs: List of parameters passed in when calling method

The invoke() method is a proxy method, which means that the method is executed when the client requests the proxy last.

How to dynamically generate proxy objects through proxy factories:

The java.lang.reflect.Proxy class is needed to generate a proxy object, which can generate any proxy object and provides a static method newProxyInstance.

 Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h);

When instantiating a proxy object, you need to pass in 3a parameter:

  • ClassLoader loader: a class loader for loading dynamic proxy classes

  • Class<?>[] interfaces: The interface implemented by the proxy class, multiple interfaces can be passed in

  • InvocationHandler h: Specify the invocation handler of the proxy class, that is, when the method in the interface is called, the proxy factory will be found and the method will be hexecuted invoke().

The dynamic agent is precisely because it satisfies the principle of opening and closing, that is, it is open for expansion and closed for modification. When facing the expansion of functional requirements, you only need to pay attention to the extended part, without modifying the original code in the system .

Dynamic proxy of JDK:

(1) How to use JDK dynamic proxy

  • Acting plants need to implement  InvocationHandlerthe interface, it will perform when called proxy method invoke()method

  • To generate a proxy object, you need to use Proxythe newProxyInstance()methods in the object, and the returned object can be forced into one of the incoming interfaces, and then call the interface method to realize the proxy

(2) Features of JDK dynamic proxy

  • The target object is mandatory to implement an interface, otherwise the JDK dynamic proxy cannot be used

to sum up:

Static proxy

 

  • Static proxy class: Actively created or generated by a third-party tool, and then compiled; before the program runs, the proxy class’s .class file already exists

  • Static proxy knows in advance what to proxy

  • Static proxy classes usually only proxy one class

Dynamic proxy

  • Dynamic agents are usually 反射机制generated dynamically when the program is running *

  • Dynamic proxy class usually proxy 接口all classes under

  • The dynamic proxy does not know in advance what to proxy, it can only be determined when it is running*

  • The invocation handler of the dynamic proxy must inherit the InvocationHandler interface in advance, and use the newProxyInstance method in the Proxy class to dynamically create the proxy class*

  • Interface-based dynamic proxy, also calledJDK动态代理

 

 

Guess you like

Origin blog.csdn.net/feikillyou/article/details/112917529