设计模式中又一个著名的模式代理模式,大多数人熟知的时静态代理,今天魔门研究一下动态代理,sun公司为我们提供了一个动态代理类Proxy和一个动态代理处理接口invocationHandler
动态代理的优点:
1.代码比较灵活
2.不会产生过多的冗杂类
我们看一个例子吧:
/**
* 接口类(日志管理)
*
*/
public interface IlogManager {
public void log();
}
/**
* 具体实现类
*
*/
public class LogManager implements IlogManager {
public void log(){
System.out.println("log..................");
}
}
/**
* 插入的功能类(切入类)
*
*/
public class computateTime {
public long getNow(){
return System.currentTimeMillis();
}
}
/**
* 处理类
*
*/
public class computateTimeHandler implements InvocationHandler {
private IlogManager logIntance;
private computateTime cTime;
/**
* 重写构造
*/
public computateTimeHandler(IlogManager logIntance,computateTime cTime) {
super();
this.logIntance = logIntance;
this.cTime = cTime;
}
//下面这个方法是关键,三个参数分别代表 需要代理的类,需要执行方法,方法参数
@Override
public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {
long before = cTime.getNow();
method.invoke(logIntance, args);
long after = cTime.getNow();
System.out.print(after-before);
return null;//没有返回值便不返回
}
}
客户端
public class Client {
public static void main(String[] args) {
IlogManager lm = new LogManager();
computateTime cTime = new computateTime();
InvocationHandler h = new computateTimeHandler(lm,cTime);
//inerfaces the list of interfaces for the proxy class to implement
//h the invocation handler to dispatch method invocations to
//生成代理类
IlogManager ProxyLm = (IlogManager) Proxy.newProxyInstance(lm.getClass().getClassLoader(),lm.getClass().getInterfaces() , h);
//代理执行方法
ProxyLm.log();
}
}
动态代理在框架方面应用最多,尤其是springmvc的aop(面向切面编程),使代码更加灵活
下一篇文章将讲解动态代理类