Java design mode proxy mode

Source: Internet
Author: User
Tags throwable

Directory

Proxy mode

1.1. static Proxy
1.2. Dynamic Agent
1.3.Cglib Proxy

Proxy mode

Proxy is a design pattern that provides additional access to the target object, that is, access to the target object through the proxy object. The advantage of this is that you can enhance the functionality of the target object by enhancing the functionality of the object, based on its implementation.
Here is a thought of programming: do not arbitrarily modify the code or methods that others have written, if you need to change, you can extend the method by proxy way

For example, to illustrate the role of the agent: suppose we want to invite a star, then not directly connect the star, but contact the Star's agent, to achieve the same goal. a star is a target, and he only takes charge of the program in the event, and other trivial things to his agent (broker) To Solve. This is an example of the idea of acting in Reality.

The diagram shows the Following:

The key point of the proxy mode is: the proxy object and the target Object. the proxy object is an extension to the target object and the target object is called

1.1. static Proxy

Static proxies, when used, need to define interfaces or parent classes that are implemented with the same interface or inherit the same parent class as the proxy Object.

Here's An example to Explain:
To simulate a save action, define an interface to save the action: iuserdao.java, and then the target object implements the method Userdao.java for this interface, at this point, if the static proxy method is used, the proxy object (userdaoproxy.java) The Iuserdao interface is also implemented in the Call. invokes the target object by invoking the proxy Object's Method.
It is important to note that the proxy object is to implement the same interface as the target object, and then invoke the method of the target object by calling the same method

Code example:

 packagecom.blankjor.proxy;/*** @desc User Save interface *@authorblankjor * @date May 30, 2017 pm 4:23:44*/ public InterfaceIuserdao {//Save Method    voidSave ();} packagecom.blankjor.proxy;/*** @desc User Save *@authorblankjor * @date May 30, 2017 pm 4:24:15*/ public classUserdaoImplementsIuserdao {@Override public voidSave () {System.out.println ("ok, the data is saved!"); }} packagecom.blankjor.proxy;/*** @desc proxy object, static proxy *@authorblankjor * @date May 30, 2017 pm 4:25:34*/ public classUserdaoproxyImplementsIuserdao {PrivateIuserdao target;  publicuserdaoproxy (iuserdao User) { this. target =user; } @Override public voidSave () {System.out.println ("start things.");        Target.save (); System.out.println ("submit things."); }} packagecom.blankjor.proxy;/*** @desc Static proxy test method *@authorblankjor * @date May 30, 2017 pm 4:27:48*/ public classMaintest { public Static voidmain (string[] Args) {//target ObjectIuserdao Userdao =NewUserdao (); //proxy object, Transfer target object to agent, establish agent relationshipUserdaoproxy proxy =NewUserdaoproxy (userdao);    Proxy.save (); }}

Execution Result:

Static Agent Summary:
1. You can extend the target function without modifying the function of the target Object.
2. disadvantages:

    • Because the proxy object needs to implement the same interface as the target object, there are many proxy classes and too many classes. at the same time, once the interface is incremented, both the target object and the proxy object are Maintained.

How to solve the disadvantages of static agents? the answer is that you can use dynamic proxy mode

1.2. Dynamic Agent

Dynamic agents have the following characteristics:
1. Proxy object, do not need to implement interface
2. The generation of proxy objects is the use of the JDK API to dynamically build proxy objects in memory (requires us to specify the type of interface that creates the proxy Object/target object Implementation)
3. Dynamic agent is also called: JDK agent, interface Agent

API for generating proxy objects in JDK
Agent Class Package: Java.lang.reflect.Proxy
The JDK implementation agent only needs to use the Newproxyinstance method, but the method needs to receive three parameters, the complete wording is:

Static Object newproxyinstance (ClassLoader loader, class<?>[] interfaces,invocationhandler h)

Note that this method is a static method in the proxy class, and the three parameters received Are:

    • ClassLoader loader,: Specifies that the current target object uses the class loader, and that the method to get the loader is fixed
    • Class<?>[] interfaces,: Type of interface implemented by the target object, using generic mode acknowledgment type
    • InvocationHandler h: Event handling, The method that triggers the event handler when the method of the target object is executed, passing the method of the current execution target object as a parameter

Code example:
Interface class Iuserdao.java and the interface implementation class, the target object Userdao is the same, no modification. on this basis, add a proxy factory class (proxyfactory.java), write the proxy class in this place, and then in the test class (the code that needs to use the proxy ), the contact of the target object and the proxy object is established, and then the same name method in the proxy object is Substituted.

Agent Factory Class: Proxyfactory.java

 packagecom.blankjor.proxy1;Importjava.lang.reflect.InvocationHandler;Importjava.lang.reflect.Method;Importjava.lang.reflect.Proxy;/*** @desc Dynamic Agent Factory *@authorblankjor * @date May 30, 2017 pm 4:32:49*/ public classProxyfactory {PrivateObject target; /*** Maintain a target object * *@paramTarget*/     publicproxyfactory (Object Target) { this. target =target; }     publicObject getproxyinstance () {returnproxy.newproxyinstance (target.getclass (). getclassloader (), target.getclass (). getinterfaces (),NewInvocationhandler () {@Override publicObject Invoke (object proxy, method method, object[] Args)throwsthrowable {System.out.println ("start thing 2."); //Execute target MethodObject returnvalue =Method.invoke (target, args); System.out.println ("commit things 2."); returnreturnvalue;    }                }); }} packagecom.blankjor.proxy1;/*** @desc Dynamic Agent test method *@authorblankjor * @date May 30, 2017 pm 4:27:48*/ public classMaintest { public Static voidmain (string[] Args) {//target ObjectIuserdao Userdao =NewUserdao (); //Original TypeSystem.out.println (userdao.getclass ()); //to the target object, create a proxy objectIuserdao Proxy = (iuserdao)Newproxyfactory (userdao). getproxyinstance (); //dynamically generated proxy objects in memorySystem.out.println (proxy.getclass ()); //Execution MethodProxy.save (); }}

Operation Result:

Summarize:
The proxy object does not need to implement the interface, but the target object must implement the interface, otherwise it cannot use the dynamic proxy

1.3.Cglib Proxy

Both the static agent and the dynamic proxy pattern above require that the target object be the target object to implement an interface, but sometimes the target object is just a separate object, and there is no interface to implement, this can be used to implement the proxy in the same way as the object subclass, this method is called: cglib agent

Cglib proxy, also known as the subclass proxy, is to build a subclass object in memory to extend the functionality of the target Object.

    • The dynamic proxy for JDK has a limitation that an object using a dynamic proxy must implement one or more interfaces, and if you want to broker a class that does not implement an interface, you can use the Cglib Implementation.
    • Cglib is a powerful, high-performance code-generation package that extends Java classes and implements Java interfaces at run Time. it is widely used by many AOP frameworks, such as spring AOP and synaop, to provide them with methods of interception (interception)
    • The bottom of the Cglib package is to convert bytecode and generate new classes by using a small block of bytecode processing framework Asm. Direct use of ASM is discouraged because it requires you to be familiar with the format and instruction set of the Jvm's internal structure including the class File.

Cglib sub-class Proxy Implementation method:
1. The Cglib jar file needs to be introduced, but the Cglib feature is already included in Spring's core package, so it can be introduced directly pring-core-3.2.5.jar .
2. Once the feature Pack is introduced, you can dynamically build subclasses in memory
3. The proxy class cannot be final, otherwise the error
4. If the target Object's method is final/static, it will not be intercepted, i.e. the target Object's additional business methods will not be Executed.

Code example:

/*** Target object, no interface implemented*/ public classUserdao { public voidSave () {System.out.println ("----has saved data!----"); }}/*** Cglib sub-class Agent Factory * Dynamically constructs a subclass object in memory for Userdao*/ public classProxyfactoryImplementsmethodinterceptor{//Maintaining target objects    PrivateObject target;  publicproxyfactory (Object Target) { this. target =target; }    //Create a proxy object for the target object     publicObject getproxyinstance () {//1. Tool classEnhancer en =NewEnhancer (); //2. Set the parent classEn.setsuperclass (target.getclass ()); //3. Setting the callback functionEn.setcallback ( this); //4. Creating subclasses (proxy objects)        returnen.create (); } @Override publicObject Intercept (object obj, method method, object[] args, methodproxy proxy)throwsthrowable {System.out.println ("start Transaction ..."); //methods for executing target objectsObject returnvalue =Method.invoke (target, args); System.out.println ("commit Transaction ..."); returnreturnvalue; }}/*** Test Class*/ public classApp {@Test public voidTest () {//target ObjectUserdao target =NewUserdao (); //Proxy ObjectUserdao Proxy = (userdao)Newproxyfactory (target). getproxyinstance (); //methods for executing proxy objectsProxy.save (); }}

Summarize:

The biggest benefit of dynamic proxies compared to static proxies is that all methods declared in the interface are transferred to the calling processor in a centralized method. When the number of interface methods is relatively high, we can handle it flexibly without having to deal with each method or combination of methods as a static proxy. Proxies are beautiful and powerful, but only interface proxies are Supported. The single-inheritance mechanism of Java doomed these dynamic proxy classes to be unable to implement the dynamic proxy for class. Fortunately there are cglib for proxy to provide a remedy. The difference between class and interface is vague, and in java8 it adds some new features that make interface more and more close to class, and when one day, Java breaks the limits of single inheritance, dynamic proxies will be more Powerful.

Reference: http://www.cnblogs.com/cenyu/p/6289209.html

http://blog.csdn.net/goskalrie/article/details/52458773

Java design mode proxy mode

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.