在上面的例子基础上,我们先添加一个通过短信来发送消息的处理类:

 

public class SmsMessage implements MessageHandler {
@Override
public void sendMessage(String msg) {
// TODO Auto-generated method stub
System.out.println("SMS Message :" + msg+" sent !");
}
}
//动态代理类
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class DynamicMessageProxy implements InvocationHandler {
private static int count;
private MessageHandler msgHandler;
public DynamicMessageProxy(MessageHandler handler) {
msgHandler = handler;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
System.out.println("++++++++=============+++++++++");
System.out.println("proxy:" + proxy.getClass());
System.out.println("method:" + method);
System.out.println("++++++++=============+++++++++");
if (args != null && args.length == 1 && checkMessage((String) args[0])) {
count++;
System.out.println("Message sent:" + count);
return method.invoke(msgHandler, args);
}
return null;
}
private boolean checkMessage(String msg) {
return msg != null && msg.length() > 10;
}
}
//下面是调用
import java.lang.reflect.Proxy;
public class MainClass {
private static void runProxy(MessageHandler handler) {
handler.sendMessage("message for test");
}
/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
// runProxy(new EmailMessage());
// System.out.println("++++++++++++++++Proxy++++++++++++++++++");
// runProxy(new MessageProxy());
MessageHandler handler = new EmailMessage();
runProxy(handler);
MessageHandler proxy = (MessageHandler) Proxy.newProxyInstance(
MessageHandler.class.getClassLoader(),
new Class[] { MessageHandler.class }, new DynamicMessageProxy(
handler));
runProxy(proxy);
System.out.println("++++++++++++++++++++++++++++++++++");
// 短信方式
handler = new SmsMessage();
runProxy(handler);
proxy = (MessageHandler) Proxy.newProxyInstance(MessageHandler.class
.getClassLoader(), new Class[] { MessageHandler.class },
new DynamicMessageProxy(handler));
runProxy(proxy);
}
}