ProxyPattern_署理模式
ProxyPattern_代理模式
1:此例演示 使用JDK代理模式,使用此模式须实现接口,对没有实现接口的类的代理可以用 CGLIB代理
package cn.proxy.test; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * 代理模式(使用JDKProxy代理) */ public class ProxyClass implements InvocationHandler { private RealInterface realInterface; // 实际被调用对象 private RealInterface warpedInterface; // 经包装过的代理对象 RealInterface bind(RealInterface realInterface){ this.realInterface = realInterface; // 生成代理对象 this.warpedInterface = (RealInterface)Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{RealInterface.class}, this); return warpedInterface; } // 将对实际接口的调用转发给 实现InvocationHandler的类 @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // 拦截方法 if("sayHello".equals(method.getName())){ return "sayHello 被拦截..."; } return method.invoke(realInterface, args); } public static void main(String[] args) { ProxyClass instance = new ProxyClass(); RealInterface proxyInstance = instance.bind(new InterfaceInstance()); System.out.println(proxyInstance.sayHello("lisi")); System.out.println(proxyInstance.sayHi("wangwu")); } } interface RealInterface { public String sayHello(String name); public String sayHi(String name); } class InterfaceInstance implements RealInterface { @Override public String sayHello(String name) { return name + " sayHello...."; } @Override public String sayHi(String name) { return name + " sayHi...."; } }