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)