設計模式中又一個著名的模式代理模式,大多數人熟知的時靜態代理,今天魔門研究一下動態代理,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(面向切面編程),使代碼更加靈活
下一篇文章將講解動態代理類