先贴代码 ,有空再写说明
package com.pattern.structure.proxy; /** * 信息接口 */ public interface Message { public void sendMessage(String value); }
package com.pattern.structure.proxy; /** * 邮箱实现类 */ public class EmailMessage implements Message { @Override public void sendMessage(String value) { System.out.println(value); } }
package com.pattern.structure.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * 动态代理 */ public class DynamicProxy implements InvocationHandler { private Object target; /** * 绑定委托对象并返回一个代理类 * @param target * @return */ public Object bind(Object target) { this.target = target; // 取得代理对象 ,要绑定接口(这是一个缺陷,cglib弥补了这一缺陷) return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(), this); } @Override public Object invoke(Object obj, Method method, Object[] aobj) throws Throwable { Object result = null; if(checkSendMessage(aobj[0])){ result = method.invoke(target, aobj); }else{ System.out.println("发送的短信为空,发不出去"); } return result; } public boolean checkSendMessage(Object value){ return value == null ? false : true; } }
package com.pattern.structure.proxy; public class Test { /** * @param args */ public static void main(String[] args) { /**************动态代理******************/ DynamicProxy dynamicProxy = new DynamicProxy(); Message emailMessageProxy = (Message)dynamicProxy.bind(new EmailMessage()); emailMessageProxy.sendMessage(null); emailMessageProxy.sendMessage("动态代理成功发送"); } }