Simple analysis of static agent and dynamic agent in Java

Source: Internet
Author: User
Tags object object

Original works, can be reproduced, but please mark the source address http://www.cnblogs.com/V1haoge/p/5860749.html

1 agent (Dynamic proxy)
Agent is divided into static agents and dynamic agents, static agent is at compile time interface, implementation class, proxy class peremptorily all manually completed, but if we need a lot of agents, each of which is so manual to create is a waste of time, and there will be a lot of duplicate code, at this time we can use dynamic agents, Dynamic agents can dynamically create proxy classes and their instances as needed during the run of a program to accomplish specific functions.
In fact, the method can be called directly to complete the function, why add an agent?
The reason is that the use of proxy mode can effectively decouple the specific implementation from the caller, and the specific implementation is completely hidden inside by the interface-oriented coding.
2, the general mode of agent implementation
In fact, the general mode of proxy is static proxy implementation mode: first create an interface (JDK proxy is interface-oriented), and then create a concrete implementation class to implement this interface, in creating a proxy class also implement this interface, the difference is that The method of implementing the class needs to implement the business logic function of the method defined in the interface, and the method in the proxy class can only invoke the corresponding method in the concrete class, so that we can call the method of the proxy class directly when we need to use the function of a method in the interface, and hide the concrete implementation class at the bottom.
First step: Define the Total interface Iuser.java

1  Package Ceshi1; 2  Public Interface Iuser {3     void Eat (String s); 4 }

Step Two: Create a concrete implementation class Userimpl.java

1  Package Ceshi1; 2  Public class Implements Iuser {3@Override4publicvoid  eat (String s) {  5 System.out.println ("I Want to eat" +s); 6 }7 }         

Step three: Create a proxy class Userproxy.java

1  PackageCeshi1;2  Public classUserproxyImplementsIuser {3     PrivateIuser user =NewUserimpl ();4     @Override5      Public voidEat (String s) {6SYSTEM.OUT.PRINTLN ("Static proxy pre-content");7       User.eat (s);8SYSTEM.OUT.PRINTLN ("Static proxy post content");9     }Ten}

Fourth step: Create a Test class Proxytest.java

1  Package Ceshi1; 2  Public class proxytest {3publicstaticvoid  main (string[] args) {     4 New userproxy (); 5 proxy.eat ("Apple"); 6 }7 }      

Operation Result:

1 static proxy predecessor content 2 I want to eat apples 3 static proxy post content

3, the implementation of dynamic agents
The mode of thinking of dynamic agent is the same as that of the previous general pattern, and it is also an interface-oriented encoding, and the creation of proxy class is decoupled from the specific class, except that the proxy class is created at different time, and the dynamic agent needs to be created in real time at runtime.
First step: Define the Total interface Iuser.java

1  Package Ceshi1; 2  Public Interface Iuser {3void  eat (String s); 4 }   

Step Two: Create a concrete implementation class Userimpl.java

1  Package Ceshi1; 2  Public class Implements Iuser {3@Override4publicvoid  eat (String s) {  5 System.out.println ("I Want to eat" +s); 6 }7 }         

Step three: Create a proxy class that implements the Invocationhandler interface

1  PackageCeshi1;2 ImportJava.lang.reflect.InvocationHandler;3 ImportJava.lang.reflect.Method;4  Public classDynamicproxyImplementsInvocationhandler {5     PrivateObject object;//an instance object used to receive a specific implementation class6     //to pass an object of a concrete implementation class using a constructor with parameters7      Publicdynamicproxy (Object obj) {8        This. Object =obj;9     }Ten     @Override One      PublicObject Invoke (Object proxy, Method method, object[] args)throwsThrowable { ASystem.out.println ("Front content"); -       Method.invoke (object, args); -System.out.println ("Post content"); the       return NULL; -     } -}

Fourth step: Create a Test class Proxytest.java

1  PackageCeshi1;2 ImportJava.lang.reflect.InvocationHandler;3 ImportJava.lang.reflect.Proxy;4  Public classProxytest {5      Public Static voidMain (string[] args) {6Iuser user =NewUserimpl ();7Invocationhandler h =Newdynamicproxy (user);8Iuser proxy = (iuser) proxy.newproxyinstance (Iuser.class. getClassLoader (),NewClass[]{iuser.class}, h);9Proxy.eat ("Apple");Ten     } One}

The result of the operation is:

1 Dynamic Agent Pre-content 2 I want to eat apples 3 dynamic agent post content

4, through the above dynamic proxy example, we will carefully analyze and study the implementation process of dynamic agent
(1) The first thing I want to say is the interface, why the JDK dynamic agent is the basic interface implementation?
Because by using the interface to the implementation of the multi-state implementation of the instance of the class, you can effectively decouple the specific implementation and the call, facilitate later modification and maintenance.
Specifically, we create a private member variable (private decoration) in the proxy class, use the interface to point to the object that implements the class (a pure polymorphic representation, an upward transformation embodiment), and then use the created instance in the method in the proxy class to invoke the corresponding method in the implementation class to complete the business logic functionality.
So, what I said before, "to completely hide a specific implementation class" Is not quite right, it can be changed to completely hide the details of the implementation class from the caller (the caller calls the method in the proxy class, not the method in the implementation class).
This is interface-oriented programming, the use of Java's polymorphic characteristics, to achieve the decoupling of program code.
(2) procedure for creating a proxy class
If you understand the static proxy, then you will find that the dynamic proxy implementation is similar to the static proxy, all need to create proxy classes, but the difference is also obvious, the creation of different ways!
The difference is reflected in the static proxy we know everything, we know which interface, which implementation class to create the proxy class, so we directly implement the same interface as the implementation class before compiling, directly in the implementation of the method to invoke the corresponding (same name) method in the implementation class, and the dynamic agent is different, We don't know when it will be created, nor do we know which interface to create, the proxy class for the implementation class (because it is created in real time at run time).
Although the two create different time, the creation method is not the same, but the principle is the same, the difference is simply: Static proxy can be directly encoded to create, and the dynamic agent is to use the reflection mechanism to abstract the proxy class creation process.
Let's take a look at the previous code to verify the above:
1th: The static proxy needs to implement the same interface as the implementation class, and the dynamic proxy needs to implement a fixed Java-provided built-in interface (an interface specifically provided to create dynamic proxies), Invocationhandler interface, Because Java provides a method invoke that can be called automatically in the interface, this is followed.
2nd: Private Object object;
Public userproxy (Object obj) {this.object = obj;}
These lines of code are similar to the code in a static proxy that defines an interface in a proxy class to an instance of a specific implementation class, which allows you to create an instance of a proxy class, creating an instance of a concrete implementation class and binding it to it (object refers to an instance of the implementation class. This instance needs to be created in the test class and used as a parameter to create an instance of the proxy class, and the private iuser user = new Userimpl () in the static proxy class is implemented, the function of a line of code is similar, why is it not the same here, but similar? The main reason is that the code of the static proxy contains the creation of an instance of the implementation class, and the creation of the implementation class in the dynamic proxy needs to be done in the test class, so this is similar here.
3rd: Invoke (Object Proxy, method, object[] args) method, which is the only method defined in the Invocationhandler interface that is called automatically when the specified method is invoked. Its parameters are: proxy instance, called method, parameter list of method
In this method we define almost the same content as the static proxy, just different from the invocation of the method, the different reasons are the same as the previous analysis (different creation time, different way of creation, i.e. reflection), the method class is an important class in the reflection mechanism, used for encapsulation method, One of the methods in this class is the Invoke (object Object,object...args) method, whose arguments represent the list of parameters for the object and method of the class to which the method is called, The parameter list here is the last parameter in the three parameters of the Invoke method passed from the test class to the proxy class (the parameter list of the calling method), in the second argument in the Invoke method passed to method (a bit verbose here).
4th: Similarities and differences in test classes
Static proxies in our test class directly create the proxy class object, using the proxy class object to invoke its method, if the other interface (this refers to other callers) to invoke the Iuser method, you can also use this method
Dynamic proxy is much more complex, first of all we want to create an instance of the implementation class mentioned earlier (complete), and then use this instance as a parameter, call the proxy constructor to create a "proxy class instance object", the reason for this is because it is not a real instance of the proxy class object, Instead of creating a real proxy class instance, the class that implements the Invocationhandler interface is strictly not a proxy class, and we can consider it to be a necessary intermediate for creating a proxy class, which is a calling processor, a class that handles method calls, is not a real proxy class, so to speak: Create a method to call the processor instance.
The following is the creation of a real proxy class instance, and the "proxy class instance object" created earlier is just a parameter
Iuser proxy = (iuser) proxy.newproxyinstance (Iuser.class.getClassLoader (), New Class[]{iuser.class}, h);
This uses the second important class proxy that the dynamic proxy relies on, where its static method is used to create a proxy instance whose arguments are: the class loader (which can be the class loader for the parent class), the interface array, the method invocation processor instance
In this case, the same polymorphism is used, the interface points to an instance of the proxy class, and the instance is used to invoke the specific method.

Simple analysis of static agent and dynamic agent in Java

Related Article

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.