Android中使用動態代理模式
阿新 • • 發佈:2019-02-10
在最近的專案開發中,在封裝業務層對外介面時,需要對所有的方法操作,例如捕獲自定義的異常訊息等,之後想到使用動態代理的方式進行處理,具體的Demo如下:
1、業務介面類和介面具體實現類
IGlobalService.java
public interface IGlobalService {
void method1();
void method2();
void method3();
}
GlobalServiceImpl.java
public class GlobalServiceImpl implements IGlobalService {
private static final String TAG = GlobalServiceImpl.class.getSimpleName();
@Override
public void method1() {
Log.i(TAG,"method1()");
}
@Override
public void method2() {
Log.i(TAG,"method2()");
}
@Override
public void method3() {
Log.i(TAG,"method3()" );
}
}
2、呼叫處理器類
動態代理的實現,需要實現InvocationHandler,並且傳入被代理物件。
public class GlobalServiceDynamicProxy implements InvocationHandler {
private static final String TAG = GlobalServiceImpl.class.getSimpleName();
private Object mProxied;//被代理的物件
private GlobalServiceDynamicProxy(Object proxied){
this .mProxied = proxied;
}
static IGlobalService createServiceProxy(IGlobalService realImpl){
//建立呼叫處理器物件
GlobalServiceDynamicProxy proxy = new GlobalServiceDynamicProxy(realImpl);
//獲取需要被代理的物件(IGlobalService型別的物件)的一組介面
Class[] classes = realImpl.getClass().getInterfaces();
//傳入被代理物件型別的ClassLoader、一組介面和呼叫處理器物件,生成動態物件
IGlobalService serviceProxy = (IGlobalService) Proxy.newProxyInstance(IGlobalService.class.getClassLoader(),classes,proxy);
return serviceProxy;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Log.i(TAG,"GlobalServiceProxy before invoke");
method.invoke(mProxied,args);
Log.i(TAG,"GlobalServiceProxy after invoke");
return null;
}
}
3、測試
GlobalServiceManager.java:
public abstract class GlobalServiceManager {
private static IGlobalService sService;
public static void init(){
if(sService==null){
sService = GlobalServiceDynamicProxy.createServiceProxy(new GlobalServiceImpl());
}
}
public static IGlobalService getService(){
if(sService==null){
init();
}
return sService;
}
}
ApplicationTest .java
public class ApplicationTest extends ApplicationTestCase<Application> {
private IGlobalService mService;
public ApplicationTest() {
super(Application.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
GlobalServiceManager.init();
mService = GlobalServiceManager.getService();
}
public void testMethod1(){
mService.method1();
}
public void testMethod2(){
mService.method2();
}
public void testMethod3(){
mService.method3();
}
}
4、測試執行結果
GlobalServiceProxy before invoke
GlobalServiceImpl: method1()
GlobalServiceImpl: GlobalServiceProxy after invoke
GlobalServiceImpl: GlobalServiceProxy before invoke
GlobalServiceImpl: method2()
GlobalServiceImpl: GlobalServiceProxy after invoke
GlobalServiceImpl: GlobalServiceProxy before invoke
GlobalServiceImpl: method3()
GlobalServiceImpl: GlobalServiceProxy after invoke