Java Design Optimization--Proxy mode

Source: Internet
Author: User

The proxy mode uses the proxy object to complete the user's request, masking the user's access to the real object.

There are many uses for proxy mode, such as blocking clients from accessing real objects directly for security reasons, or using proxy objects to handle technical details in remote methods in a remote invocation, or encapsulating the real objects for the purpose of lifting the system to achieve lazy loading.

When the system starts, the most resource-consuming method is separated by the agent mode, which can speed up the system startup and reduce the user's waiting time. When the user is actually doing the query, the proxy class loads the real class and completes the user request. This is the purpose of using proxy mode to achieve lazy loading.

1. Static Proxy implementations:

Topic Interface:

1  Public Interface idbquery {2    String request (); 3 }

Real theme:

1  Public classDbqueryImplementsIdbquery {2      PublicDbquery () {3         Try {4Thread.Sleep (10000);5}Catch(Exception e) {6 e.printstacktrace ();7         }8     }9      PublicString request () {Ten         return"String Request"; One     } A}

Proxy class:

1  Public classIdbqueryproxyImplementsIdbquery {2     Privatedbquery dbquery;3      PublicString request () {4         if(dbquery==NULL)5Dbquery =Newdbquery ();6         returndbquery.request ();7     }8}

Finally, the main function:

1  Public class Proxytext {2      Public Static void Main (string[] args) {3         New idbqueryproxy (); 4      5} 6}         

Static proxies note that the proxy class is the real class implementation of the common interface, and the proxy class refers to the real class object, the time-consuming operation in the proxy class method is implemented.

Dynamic Agent:

Dynamic proxy classes are dynamically generated when the agent is run. That is, the byte code of the proxy class is generated at run time and loaded into the current classloader. Compared with static proxy, dynamic agent does not need to encapsulate a formal package class for real attention, if the topic interface is many, it is very annoying to write an agent method for each interface, if the interface is changed, the real class and the proxy class need to change, this is not conducive to system maintenance; The use of some dynamic proxy generation methods can even be run to specify the execution logic of the proxy class, thus greatly improving the flexibility of the system.

Topic Interface:

1  Public Interface idbquery {2    String request (); 3 }

JDK proxy class:

1  Public classJdbdbqueryhandlerImplementsinvocationhandler{2Idbquery Idbquery =NULL;3 @Override4      Publicobject Invoke (Object proxy, Method method, object[] args)5             throwsThrowable {6         if(idbquery==NULL){7Idbquery =Newdbquery ();8         }9         returnidbquery.request ();Ten     } One      Public Staticidbquery Createjdbproxy () { AIdbquery Jdkproxy =(idbquery) proxy.newproxyinstance (Classloader.getsystemclassloader (), -                 NewClass[]{idbquery.class},NewJdbdbqueryhandler ()); -System.out.println ("Jdbdbqueryhandler.createjdbproxy ()"); the         returnJdkproxy; -     } -  -}

Main function:

 1  public  class   Proxytext { 2  public  static  void   main (string[] args) { 3  idbquery idbquery = Jdbdbqueryhandler.createjdbproxy ();  4   System.out.println (Idbquery.request ()); 
    5   " 6 } 

In addition, you can use Cglib and javassist dynamic proxies similar to JDK dynamic proxies, but JDK dynamic classes are created the fastest because the built-in implementation of the Difineclass () method is defined as a native implementation, so performance is better than others. On the function call of the proxy class, the dynamic agent of the JDK is inferior to the cglib and javassist dynamic agents, while the javassist dynamic agent has the worst performance quality and not even the JDK implementation. In the actual development application, the method invocation frequency of proxy class is much higher than the actual generation frequency of proxy class, so the performance of dynamic Agent's method call should be the focus of performance. The JDK dynamic agent enforces a unified interface for proxy classes and true themes, and cglib and javassist dynamic proxies do not have such requirements.

In Java, the implementation of dynamic agent involves the use of ClassLoader, taking Cglib as an example, briefly describes the dynamic class loading process. Using Cglib to generate dynamic proxies, you first need to generate an instance of the enhancer class and develop a callback class for handling the proxy business. In the Enhancer.create () method, the byte code of the proxy class is generated using the Defaultgeneratorstrategy.generate () method and saved in a byte array. It then calls the Reflectutils.defineclass () method, which, through reflection, calls the Classloader.defineclass () method, loads the bytecode into the ClassLoader and completes the class loading. Finally, the dynamic class instance is generated by reflection through the Reflectutils.newinstance () method, and the instance is returned. Others are different from the details of the process, but the generation logic is the same.

Java Design Optimization--Proxy mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.