Package chart03.proxy;/*** enhancement operation, for the extension of the proxy object * @ author heshengjun **/public interface iadvise {public abstract void dobefore (); public abstract void doafter ();}
Package chart03.proxy; public class adviseimpl implements iadvise {@ overridepublic void dobefore () {system. Out. println ("painter is ready to draw .... ") ;}@ Overridepublic void doafter () {system. Out. println (" painter finished painting ");}}
Package chart03.proxy;/*** interface of the object needing proxy * @ author heshengjun **/public interface ipicshow {public abstract void show ();}
Package chart03.proxy; import Java. lang. reflect. invocationhandler; import Java. lang. reflect. method; import Java. lang. reflect. proxy; public class pichardler implements invocationhandler {private iadvise advise; private ipicshow PIC; Public pichardler (iadvise advise) {This. advise = advise;} public object BIND (ipicshow pic) {This. PIC = PIC; return proxy. newproxyinstance (PIC. getclass (). getclassloader (), Pic. getclass (). getinterfaces (), this);} public object invoke (Object proxy, method, object [] ARGs) throws throwable {object OBJ = NULL; system. out. println (ARGs); If ("show ". equals (method. getname () {This. advise. dobefore (); OBJ = method. invoke (PIC, argS); this. advise. doafter (); Return OBJ;} else {return method. invoke (PIC, argS );}}}
Package chart03.proxy; import java. Lang. Reflect. invocationhandler;/*** dynamic proxy Design Pattern * describes the basic idea of a dynamic proxy. Separate basic functions. * Design idea * 1. Design a proxy class and interface * 2. design an enhanced class and interface * 3. Design a proxy class processing class, implement invocationhardler * 4. Create a test class ** key: Design proxy class * field: enhancement Method: the enhancement object is passed in through the constructor * the proxy object is returned through a custom method bind * the method of the proxy object can be called in the test class. * @ Author heshengjun **/public class proxydesign {public static void main (string [] ARGs) {ipicshow PIC = new picshow (); iadvise advise = new adviseimpl (); pichardler handler = new pichardler (advise); ipicshow proxy = (ipicshow) handler. BIND (PIC); proxy. show ();}}