本文共 4265 字,大约阅读时间需要 14 分钟。
package com.zj.proxy; public interface Subject { void operation1(); void operation2(String arg); } |
package com.zj.proxy; public class RealSubject implements Subject { public void operation1() { System. out .println( "Realer do operation1" ); } public void operation2(String arg) { System. out .println( "Realer do operation2 with " + arg); } } |
package com.zj.proxy; public class ProxySubject implements Subject { private Subject proxied ; // 被代理对象 public ProxySubject(Subject proxied) { this . proxied = proxied; } public void operation1() { System. out .println( "Proxyer do operation1" ); proxied .operation1(); } public void operation2(String arg) { System. out .println( "Proxyer do operation2 with " + arg); proxied .operation2(arg); } } |
package com.zj.proxy.client; import com.zj.proxy.Subject; import com.zj.proxy.RealSubject; import com.zj.proxy.ProxySubject; public class SimpleProxyDemo { public static void consumer( Subject subject) { subject.operation1(); subject.operation2( "ZJ" ); } public static void main(String[] args) { RealSubject real = new RealSubject(); System. out .println( "===Without Proxy===" ); consumer(real); System. out .println( "===Use Proxy===" ); consumer( new ProxySubject(real)); } } |
package java.lang.reflect; public interface InvocationHandler { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable; } |
package com.zj.proxy.dynamic; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class DynamicProxyHandler implements InvocationHandler { private Object proxied ; public DynamicProxyHandler(Object proxied) { this . proxied = proxied; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System. out .println( "**** proxy: ****\n" + proxy.getClass() + "\nmethod: " + method + "\nargs: " + args); if (args != null ) for (Object arg : args) System. out .println( " " + arg); return method.invoke( proxied , args); } } |
package com.zj.proxy.client; import java.lang.reflect.Proxy; import com.zj.proxy.Subject; import com.zj.proxy.RealSubject; import com.zj.proxy.dynamic.DynamicProxyHandler; public class DynamicProxyDemo { public static void consumer(Subject subject) { subject.operation1(); subject.operation2( "ZJ" ); } public static void main(String[] args) { RealSubject real = new RealSubject(); System. out .println( "===Without Proxy===" ); consumer(real); System. out .println( "===Use Proxy===" ); Subject proxy = (Subject) Proxy.newProxyInstance(Subject. class .getClassLoader(), new Class[] { Subject. class }, new DynamicProxyHandler(real)); consumer(proxy); } } |