最近在繼續iPhone
業務的同時還須要從新拾起Android
。在有些生疏的狀況下,決定從Android
源碼中感悟一些Android
的風格和方式。在學習源碼的過程當中也發現了一些通用的模式,但願經過一個系列的文章總結和分享下。
代理模式爲其餘對象提供一種代理以控制對這個對象的訪問。代理還分紅遠程代理、虛代理、保護代理和智能指針等。Android系統中利用AIDL定義一種遠程服務時就須要用到代理模式。以StatusBarManager爲例,其代理模式的類圖以下:
主要的實現代碼以下:
public class StatusBarManager {
......
private Context mContext;
private IStatusBarService mService;
private IBinder mToken = new Binder();
StatusBarManager(Context context) {
mContext = context;
mService = IStatusBarService.Stub.asInterface(
ServiceManager.getService(Context.STATUS_BAR_SERVICE));
}
public void disable(int what) {
try {
mService.disable(what, mToken, mContext.getPackageName());
} catch (RemoteException ex) {
// system process is dead anyway.
throw new RuntimeException(ex);
}
}
public void expand() {
try {
mService.expand();
} catch (RemoteException ex) {
// system process is dead anyway.
throw new RuntimeException(ex);
}
}
public void collapse() {
try {
mService.collapse();
} catch (RemoteException ex) {
// system process is dead anyway.
throw new RuntimeException(ex);
}
}
public void setIcon(String slot, int iconId, int iconLevel) {
try {
mService.setIcon(slot, mContext.getPackageName(), iconId, iconLevel);
} catch (RemoteException ex) {
// system process is dead anyway.
throw new RuntimeException(ex);
}
}
public void removeIcon(String slot) {
try {
mService.removeIcon(slot);
} catch (RemoteException ex) {
// system process is dead anyway.
throw new RuntimeException(ex);
}
}
public void setIconVisibility(String slot, boolean visible) { try { mService.setIconVisibility(slot, visible); } catch (RemoteException ex) { // system process is dead anyway. throw new RuntimeException(ex); } } } 其中做爲代理的StatusBarManager經過 IStatusBarService.Stub.asInterface(ServiceManager.getService(Context.STATUS_BAR_SERVICE))獲取到了遠程服務,用戶經過StatusBarManager同真正的服務交互。