Java Proxy mode (implemented via public interface)

Source: Internet
Author: User

A common implementation of proxy mode is to define an interface or abstract class, and derive the target subclass, and the proxy subclass. We want to manipulate the method in the target subclass, and many times, we need to add additional processing to the methods in the directory subclass, if the log function, conditional judgment, etc., it is necessary to use the proxy class.

/*** Public interface of proxy subclass and Target subclass *@authorRongxinhua **/ Public InterfaceMyInterface { Public voiddooperation ();}/*** Target sub-class *@authorRongxinhua **/ Public classRealclassImplementsMyInterface {/*** We want to implement the target method*/@Override Public voiddooperation () {System.out.println ("Dooperation"); }} and without using proxy mode, this is how we do the target method: Realclass realobj=NewRealclass ();    Realobj.dooperation (); //calling the target methodprint-time output: dooperation and we're going to add additional processing, we can use the proxy class:/*** Proxy sub-class *@authorRongxinhua **/ Public classProxyclassImplementsMyInterface {PrivateMyInterface Realobj;//Target sub-class object         PublicProxyclass (MyInterface realobj) { This. Realobj =Realobj; }        /*** Method of calling the target subclass and adding pre-processing and post-processing to it*/@Override Public voiddooperation () {dobefore ();        Realobj.dooperation ();    Doafter (); }        /*** Related processing before the target method call*/    Private voidDobefore () {System.out.println ("Dobefore"); }        /*** Related processing after the target method call*/    Private voidDoafter () {System.out.println ("Doafter"); }} with the proxy class, we can execute the target method like this: Proxyclass proxyobj=NewProxyclass (NewRealclass ());    Proxyobj.dooperation (); //calling the Dooperation method from a proxy objectprint-time output: Dobeforedooperationdoafter

Java Proxy mode (implemented via public interface)

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.