1. What is the proxy mode?

The first is a design pattern that acts as a proxy for the target class.

2. Why use proxy mode?

Enhance the target class and reduce the memory footprint of the target class object load without changing the target class.

3. What is static proxy? Dynamic proxy?

Static proxy requires us to implement the proxy class manually, while dynamic proxy is generated by the JDK for example.

4. Static proxy

    

Sell sell=new ProTarget(); sell.openSell(); A series of enhancements to the target class can be made here...... I'm the target classCopy the code

This is how static proxies are implemented.

5. Dynamic Proxy

Speaking of dynamic proxy in fact, we can be seen everywhere in the application framework, with AOP students know that it is actually enhanced, this is not the mapping just said static proxy!! So why use dynamic proxies when you have static proxies? Is static not fragrant? It is not sweet, because we now just illustrate the example, the logic is clear, when the business is complex, interface and implementation of many cases of static proxy it is not sweet, just think about it, if every implementation class to write a proxy class, it is not tiring individuals, so dynamic proxy emerged.

Take the JDK’s dynamic proxy for example:

Java.lang.reflect. Proxy has a method, newProxyInstance, used to generate the Proxy class.Copy the code

Let’s first look at the method’s arguments and return:

ClassLoader loader,Class<? >[] interfaces,InvocationHandler h

@param loader The class loader to define the proxy class interfaces @param interfaces the list of interfaces for the proxy @Param h The Invocation handler to dispatch method invocations to the invocation handler @return A proxy instance with the specified invocation handler of a proxy class that is defined by the specified class loader and That implements the specified interfaces means that an instance of the agent is returned based on the three specified parameters.Copy the code

The third parameter call is something we need to implement ourselves:

Generate dynamic proxies for target classes:

Sell sell=new Target();
Sell proxy=(Sell)new JdkInvocationHandler().getInstance(sell);
Copy the code