示例来源于《Java 学习笔记》
1、首先建立一个接口IHello: 定义所要代理的接口:
public interface IHello {
public void hello(String name) ;
}
2、建立一个实现了该接口的类:
public class Hello implements IHello {
@Override
public void hello(String name) {
System.out.println("Hello"+name);
}
}
3、实现一个实现了java.lang.reflect.InvocationHandler接口的处理器类,并实现其invoke()方法
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.logging.Level;
import java.util.logging.Logger;
public class LogHandler implements InvocationHandler {
private Logger logger = Logger.getLogger(this.getClass().getName());
private Object delegate;
//绑定要代理的对象
public Object bind(Object delegate) {
this.delegate = delegate;
return Proxy.newProxyInstance(delegate.getClass().getClassLoader(), delegate.getClass().getInterfaces(), this);
}
//代理要调用的方法,并在其前后增加行为
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = null;
try {
logger.log(Level.INFO, "method start ...");
result = method.invoke(delegate, args);
logger.log(Level.INFO,"method end ...");
} catch (Exception e) {
logger.log(Level.INFO, e.toString());
}
return result;
}
}
4、代理的使用:
public class T {
/**
* @param args
*/
public static void main(String[] args) {
LogHandler handler = new LogHandler();
IHello speaker = new Hello();
IHello speakerProxy = (IHello) handler.bind(speaker);//建立代理对象
speakerProxy.hello("justin");
}
}
拓展阅读:
1\java动态代理(JDK和cglib) http://www.cnblogs.com/jqyp/archive/2010/08/20/1805041.html里面写得很详细,还有cglib的拓展
2\菜鸟课堂:几个动态代理Proxy工具性能比较 http://tech.ccidnet.com/art/3539/20091019/1913651_1.html
3、什么是Javassist http://hi.baidu.com/jackfrued/item/be340ce278b5daa8c10d75a1
...看来代理模式还真是个有话可说的模式,以后要找个时间好好总结研究一下