Java proxy mode

Source: Internet
Author: User
Tags object object throwable ticket

Agent Mode Learning

    • Basic concepts
    • Specific implementation methods

A basic concept

Provides a proxy for other objects to control access to this object. Proxy Objects act as intermediaries, removing feature services or adding additional services.

Two realization mode

    • Static proxy
    • Dynamic Agent

1. Static Agent

Static proxy implementations are: inheritance and implementation of the interface in two ways, usually choose the latter.

1  PackageCn.np.proxy.staticproxy;2 3 /**4  * @authorNP5 * @date 2018/9/96 * target object implementation Interface7  */8  Public InterfaceTickethandler {9     voidSaleticket ();Ten}
1  PackageCn.np.proxy.staticproxy;2 3 /**4  * @authorNP5 * @date 2018/9/96 * Target object implementation class7  */8  Public classTrainstationImplementstickethandler{9 Ten @Override One      Public voidSaleticket () { ASystem.out.println ("Sales train ticket-ticketing from the railway station"); -     } -}
1  PackageCn.np.proxy.staticproxy;2 3 /**4  * @authorNP5 * @date 2018/9/96 * Static proxy class7  */8  Public classTicketproxyImplementstickethandler{9 Ten     Privatetrainstation trainstation; One  A      PublicTicketproxy () { -  -     } the  -      Publicticketproxy (trainstation trainstation) { -          This. trainstation=trainstation; -     } +  - @Override +      Public voidSaleticket () { ASystem.out.println ("Pre-ticketing-proxy class"); at         if(NULL!=trainstation) { - Trainstation.saleticket (); -         } -System.out.println ("post-ticketing-proxy class"); -     } -}
1  PackageCn.np.proxy.staticproxy;2 3 /**4  * @authorNP5 * @date 2018/9/96  *7 * Static Agent testing8  */9  Public classClient {Ten  One      Public Static voidMain (string[] args) { ATrainstation trainstation=Newtrainstation (); - Trainstation.saleticket (); -  theTicketproxy ticketproxy=NewTicketproxy (trainstation); - Ticketproxy.saleticket (); -     } -}

Output Result:

Sales train ticket-ticketing from train station ticketing-agent class sales train tickets-ticket issued from the station after the ticket-agent class

Summarize:

Advantages: The target object is extended and intercepted without modification of the object;

Disadvantage: Because the proxy object needs to implement the same interface as the target object, which leads to the complex maintenance of the proxy class, the same logical proxy class needs to implement the interface of different types of target objects, such as the above example need agent sales plane ticket, car ticket and so on.

2. Dynamic Agent

Dynamically obtains an instance of the target object in memory and executes the target method. There are two ways of implementation: JDK Dynamic agentand Cglib Dynamic agent, JDK dynamic agent can only proxy classes that implement class interfaces; Cglib dynamic proxies are implemented for classes (inheritance).

Steps for the JDK dynamic Agent implementation:

    • Dynamic proxy class implements interface Java.lang.reflect.InvocationHandler
    • Creating a proxy class and interface
    • Call Proxy.newproxyinstance (ClassLoader loader, class<?>[] Interfaces,invocationhandler h) to dynamically create proxy classes
 Package cn.np.proxy.dynamic; /**  @author*/Publicinterface  tickethandler    { void saleticket ();}  Public Interface Loghandler {    void  writelog ();}

1  Packagecn.np.proxy.dynamic;2 3 ImportJava.lang.reflect.InvocationHandler;4 ImportJava.lang.reflect.Method;5 6 /**7  * @authorNP8 * @date 2018/9/99 * Dynamic proxy classTen  */ One  Public classTicketdynamicproxyImplementsInvocationhandler { A  -     PrivateObject Target; -  the      PublicTicketdynamicproxy (Object object) { -target=object; -     } -  +     /** -      * @paramProxy Object +      * @parammethod is proxied object methods A      * @paramargs is proxy object method parameters at      * @return -      * @throwsThrowable -      */ - @Override -      PublicObject Invoke (Object proxy, Method method, object[] args)throwsThrowable { -SYSTEM.OUT.PRINTLN ("Dynamic agent-before executing target method"); inObject result=Method.invoke (target); -SYSTEM.OUT.PRINTLN ("Dynamic agent-after executing the target method"); to         returnresult; +     } -}
1  Packagecn.np.proxy.dynamic;2 3 4 Importjava.util.Date;5 6 /**7  * @authorNP8 * @date 2018/9/99  */Ten  Public classTrainstationImplementstickethandler,loghandler{ One  A @Override -      Public voidSaleticket () { -System.out.println ("Sales train ticket-ticketing from the railway station"); the     } -  - @Override -      Public voidWritelog () { +System.out.println ("Log, Current time is:" +NewDate (). GetTime ()); -     } +}
1  Packagecn.np.proxy.dynamic;2 3 ImportJava.lang.reflect.InvocationHandler;4 ImportJava.lang.reflect.Proxy;5 6 /**7  * @authorNP8 * @date 2018/9/99  */Ten  Public classClient { One  A      Public Static voidMain (string[] agrs) { -Trainstation trainstation=Newtrainstation (); -Class<?> clz=Trainstation.getclass (); theClass<?>[] Interfaces=clz.getinterfaces (); -  -Invocationhandler handler=NewTicketdynamicproxy (trainstation); -  +Tickethandler tickethandler=(Tickethandler) proxy.newproxyinstance (Clz.getclassloader (), interfaces,handler); - Tickethandler.saleticket (); +  ALoghandler loghandler=(Loghandler) proxy.newproxyinstance (Clz.getclassloader (), interfaces,handler); at Loghandler.writelog (); -  -     } -}

Output Result:

Dynamic Agent-Execute target method before selling train tickets-tickets from the railway station dynamic agent-dynamic agent after executing the target method-log before the target method is executed, the current time is: 1536478014151 dynamic agent-After executing the target method

Advantage: The proxy class does not need to implement the same interface as the target class, adding flexibility

Disadvantage: The proxy object does not need to implement the interface, but the target object must implement the interface, otherwise the JDK dynamic agent cannot be used.

Java 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.