The proxy mode of Java design pattern

Source: Internet
Author: User

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

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

There are three types of proxy modes in Java: Static agent, dynamic agent, Cglib agent

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.

code example:

Person interface

/** * Define an interface * @ClassName: Person  * @Description: TODO (here is a word describing the role of this  Class)@author  Timyang  * @date 2018-1-18 pm 9:53:33  */Publicinterface  person        {  Public void eat ();}

Personimpl Target Class (the class being proxied)

 Public class Implements Person {    publicvoid  eat () {        System.out.println ("I'm eating!") ");    }}

Proxyimpl proxy class

/*** This is the proxy class * @ClassName: Proxyimpl * @Description: TODO (here in a word describing the role of this class) *@authorTimyang * @date 2018-1-18 pm 9:56:04 **/ Public classProxyimplImplementsPerson {PrivatePersonimpl person;  PublicProxyimpl (Personimpl person) { This. person =Person ; }         Public voideat () {System.out.println ("Wash your hands before you eat!" ");        Person.eat (); System.out.println ("Brush your teeth after dinner!" "); }}

Clienttest Test class

 Public classClienttest {/*** @Title: Main * @Description: TODO (here is a word describing the effect of this method) *@param @paramargs settings file *@returnvoid return type *@throws      */     Public Static voidMain (string[] args) {Personimpl person=NewPersonimpl (); Proxyimpl P=NewProxyimpl (person);    P.eat (); }}

Summary: using the JDK's static proxy, both the target class and the proxy class must implement the interface

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

The JDK implementation agent only needs to use the Newproxyinstance method, but the method needs to receive three parameters, the complete wording is:

Static newproxyinstance (ClassLoader loader, class<?>[] Interfaces,invocationhandler h)
    • 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 executing the method of the target object, passes the method of the current execution target object as a parameter

code example:

Person Interface Class

 Public Interface Person {        publicvoid  eat ();}

Personimpl Target Class (proxy class)

/** * Java dynamic Proxy, the object being proxied must implement Interface * @ClassName: Personimpl  * @Description: TODO (here is a word describing the role of this class  )@author  Timyang  * @date 2018-1-18 PM 9:10:25  **publicclass  Implements person {    publicvoid  eat () {        System.out.println ( "I'm having dinner!" ");    }}

Proxyfactory proxy class (proxy class does not implement Interface)

/*** Proxy class * @ClassName: Proxyfactory * @Description: TODO (here in a word describing the role of this class) *@authorTimyang * @date 2018-1-18 pm 10:12:56 **/ Public classProxyfactory {//the object being proxied    PrivateObject object;  Publicproxyfactory (Object object) { This. Object =object; }         PublicObject getproxyinstance () {returnProxy.newproxyinstance (Object.getclass (). getClassLoader (), Object.getclass (). Getinterfaces (),NewInvocationhandler () { PublicObject Invoke (Object proxy, Method method, object[] args)throwsthrowable {System.out.println ("Wash your hands before you eat!" "); Object Proxyobject=Method.invoke (object, args); System.out.println ("Wash the dishes after dinner!" "); returnProxyobject;    }        }); }}

Clienttest Test Class

 Public classClienttest {/*** @Title: Main * @Description: TODO (here is a word describing the effect of this method) *@param @paramargs settings file *@returnvoid return type *@throws      */     Public Static voidMain (string[] args) { person person=NewPersonimpl (); Person Proxyperson= (person)Newproxyfactory (person). Getproxyinstance ();    Proxyperson.eat (); }}

Summary: 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

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 a 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:

Personimpl the class being proxied

/** * Java cglib agent * @ClassName: Personimpl  * @Description: TODO (here is a word describing the role of this  Class)@author  Timyang  * @date 2018-1-18 PM 9:10:25  **publicclass  Personimpl {      Public void eat () {        System.out.println ("I'm eating!") ");    }}

Proxyfactory proxy Object

 Public classProxyfactoryImplementsmethodinterceptor{//the object being proxied    PrivateObject object;  Publicproxyfactory (Object object) { This. Object =object; }         PublicObject getproxyinstance () {//Cglib Agent's toolbarEnhancer en =Newenhancer (); //Set Parent classEn.setsuperclass (Object.getclass ()); //Setting the callback functionEn.setcallback ( This); //Creating subclasses (proxy objects)        returnen.create (); }     PublicObject Intercept (Object obj, Method method, object[] args, Methodproxy proxy)throwsthrowable {System.out.println ("Wash your hands before you eat!" "); Object Proxyobject=Method.invoke (object, args); System.out.println ("Wash the dishes after dinner!" "); returnProxyobject; }}

Clienttest Test class

 Public classClienttest {/*** @Title: Main * @Description: TODO (here is a word describing the effect of this method) *@param @paramargs settings file *@returnvoid return type *@throws      */     Public Static voidMain (string[] args) {Personimpl person=NewPersonimpl (); Personimpl Proxyperson= (Personimpl)Newproxyfactory (person). Getproxyinstance ();    Proxyperson.eat (); }}

Summary: In spring AOP programming: If the target object that joins the container has an implementation interface, use the JDK proxy, and if the target object does not implement the interface, use the Cglib proxy

The proxy mode of Java design pattern

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.