Static Proxy:
Isubject:
/*** @ Author com. Tiantian * @ version Creation Time: 1:49:29 */public interface isubject {public void request ();}
Realsubject (real role ):
/*** @ Author COM. tiantian * @ version Creation Time: 1:51:37 */public class realsubject implements isubject {@ override public void request () {system. out. println ("realsubject requesting ");}}
Proxysubject (proxy class ):
/*** @ Author COM. tiantian * @ version Creation Time: 1:52:22 */public class proxysubject implements isubject {private realsubject; Public proxysubject () {realsubject = new realsubject ();} @ override public void request () {system. out. println ("do something before"); realsubject. request (); system. out. println ("do something after ");}}
Test (client test ):
/*** @ Author COM. tiantian * @ version Creation Time: 1:54:47 */public class test {public static void main (string [] ARGs) {isubject proxysubject = new proxysubject (); proxysubject. request ();}}
Bytes ------------------------------------------------------------------------------------------------------------------------------
Dynamic Proxy:
Isubject:
/*** @ Author com. Tiantian * @ version Creation Time: 2:51:31 */public interface isubject {public void request ();}
Realsubject:
/*** @ Author COM. tiantian * @ version Creation Time: 2:52:00 */public class realsubject implements isubject {@ override public void request () {system. out. println ("realsubject requesting ");}}
Subjectinvocationhandler (call processing class ):
/*** @ Author COM. tiantian * @ version Creation Time: 2:54:38 * call processing class */public class subjectinvocationhandler implements invocationhandler {private object OBJ; Public subjectinvocationhandler (Object OBJ) {This. OBJ = OBJ;}/*** generate proxy factory * @ author COM. tiantian * @ Param realobj * @ return returns the generated proxy class */public static object getproxyinstancefactory (Object realobj) {class <?> Classtype = realobj. getclass (); Return proxy. newproxyinstance (classtype. getclassloader (), classtype. getinterfaces (), new subjectinvocationhandler (realobj);} @ override public object invoke (Object proxy, method, object [] ARGs) throws throwable {system. out. println ("before"); method. invoke (OBJ, argS); system. out. println ("after"); return NULL ;}}
Test:
/*** @ Author COM. tiantian * @ version Creation Time: 2:56:25 */public class test {public static void main (string [] ARGs) {realsubject = new realsubject (); // invocationhandler handler = new subjectinvocationhandler (realsubject); // isubject subject = (isubject) proxy. newproxyinstance (realsubject. getclass (). getclassloader (), // realsubject. getclass (). getinterfaces (), Handler); isubject subject = (isubject) subjectinvocationhandler. getproxyinstancefactory (realsubject); Subject. request ();}}