Dynamic proxy (2) -- Dynamic proxy and AOP

Source: Internet
Author: User

According to the proxy and invocationhandler described above, it is difficult to see the advantages of this dynamic proxy. The following describes a more practical dynamic proxy mechanism.

As long as we develop a software system in actual use, the same code will always repeat. In this case, the most common practice is: select the code to "copy" and "Paste" to immediately implement the system's functions. If you only look at the software functions, they have completed the software development. The system implemented using the above method may feel indifferent during software development, but if one day you need to modify the public part of the program, it means to open multiple source codes for modification. If this dark code segment is used in 100 or even 1000 places, the effort to modify and maintain this code will become a nightmare.

In this case, most of the less experienced development will define a public code block as a method, and then let the other three code blocks directly call this method. In this case, you only need to modify the public code once. The code segment that calls this method does not need to be modified, no matter how many times it is called. As long as the called method is modified, all the places where the method is called Change naturally. This method greatly reduces the complexity of software maintenance.

However, the biggest problem with this method is that the parts of each call to the public code block are coupled with the public code block, which is not conducive to debugging and testing. The most ideal effect is that the public code block is executed without being directly called in hard-coding mode in the program. This effect can be achieved through dynamic proxy.

Because JDK dynamic proxy can only create a dynamic proxy for a specified interface, the following provides a dog interface. The interface code is very simple and only two methods are defined in this interface.

Interface dog {// info () method declaration public void Info (); // run () method declaration public void run ();}

The above interface only defines two methods and does not provide method implementation. If we directly use proxy to create a dynamic proxy object for this interface, the execution of all methods of the dynamic proxy object will be the same. In this case, we will first provide a simple implementation class for the dog interface: gundog

Class gundog implements dog {// info method implementation, print only one string @ overridepublic void Info () {system. out. println ("I Am a hound");} // run method implementation, print only one string @ overridepublic void run () {system. out. println ("I am running fast ");}}

The above Code does not have any special points. The dog implementation class only provides a simple implementation for each method. Back to the function we need to implement: Make public code appear in the class that needs to be called in a hard-coded manner. In this case, we assume that the info () and run () Methods represent the methods to call public code. Therefore, when the program executes the info () and run () methods, it must call a common method, however, this method is not called by hard encoding. The following provides two common methods in the dogutil class.

Class dogutil {// The first interceptor method public void Method1 () {system. out. println ("----------- simulate the first common method -----------");} // The second interceptor method public void method2 () {system. out. println ("----------- simulate the second common method -----------");}}

With the help of proxy and invocationhandler, it can be implemented: when the program calls the info () method and run () method, the system can "automatically" Convert Method1 () and method2 () two common methods are inserted into the info () and run () methods for execution.

The key to this program is the following myinvokationhandler class, which is an invovationhandler implementation class. The invoke method of this implementation class will be implemented as a proxy method.

Class myinvokationhandlerpro implements invocationhandler {// Private object target to be proxy; Public void settarget (object target) implements this.tar get = target;} // when all methods of the dynamic proxy object are executed, will be replaced with the following invoke method: Public object invoke (Object proxy, method, object [] ARGs) throws exception {dogutil du = new dogutil (); // execute the Method1 method du in the dogutil object. method1 (); // use target as the main call to execute method object result = method. invoke (target, argS); // execute the method2 method du in the dogutil object. method2 (); return result ;}}

The above Code includes a line of key code when implementing the invoke method. This line of code uses the target as the main call to execute the method through reflection. This is the original method used to call the target object. Call the Method1 () method of the dogutil object before the bold code, and then call the method2 () method of the dogutil object.

The following provides a myproxyfactory class for the Program. This object generates a dynamic proxy instance for the specified target.

Class myproxyfactory {// generate a dynamic proxy object public static object getproxy (object target) throws exception {// create a myinvokationhandler object myinvokationhandlerpro handler = new myinvokationhandlerpro (); // set the target object handler for myinvokationhandler. settarget (target); // create and return a dynamic proxy return proxy. newproxyinstance (target. getclass (). getclassloader (), target. getclass (). getinterfaces (), Handler );}}

The above dynamic proxy factory class provides a getproxy method, which generates a dynamic proxy object for the target object, which implements the same interface as the target object, so it has the same public method. In this sense, dynamic proxy objects can be used as target objects. When a program calls a specified method of a dynamic proxy object, it will actually become the invoke Method for executing the myinvokationhandler object. For example, to call the info () method of the dynamic proxy object, the program will start to execute the invoke method. The procedure is as follows:

1. Create a dogutil instance

2. Execute the Method1 () method of the dogutil instance.

3. Execute the info () method using the reflection target as the caller.

4. Execute the method2 () method of the dogutil instance.

When we see the execution process above, the reader should have discovered that when we use a dynamic proxy object to replace the target object, the proxy object method will implement the requirements before the class: Program Execution Info (),

The general methods of Method1 () and method2 () can be called in the run () method, but the methods of gundog do not call Method1 () and method2 () in hard encoding ().

The main program is provided below to test the effect of this dynamic proxy.

Public class testproxy {public static void main (string [] ARGs) throws exception {// create an original gundog object as targetdog target = new gundog (); // create dynamic proxy dog = (DOG) myproxyfactory with the specified target. getproxy (target); dog.info (); dog. run ();}}

In the above program, the dog object is actually a dynamic proxy object, but this dynamic proxy object also implements the dog-like interface, so it can also be used as a dog object. When the program executes the info () and run () Methods of the dog, it will actually first execute the dogutil Method1 () in the execution of the info () and run () Methods of the target object () shows the result of executing method2 () in dogutil.

It is not difficult to find that dynamic proxy can be used for flexible decoupling. Generally, when we use a proxy to generate a dynamic proxy, it usually does not generate a dynamic proxy out of thin air, which does not have much practical significance. A dynamic proxy is usually generated for the specified target object.

This kind of dynamic proxy is called the AOP proxy in AOP (Aspect Orient program, for Aspect-Oriented Programming). The AOP proxy can replace the target object, and the AOP proxy contains all the target objects. However, the methods in the AOP proxy are different from those in the target object: The methods in the AOP proxy can insert some general processing before executing the target method.

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.