Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android IOC 與 RoboGuice(三):注入設定與模組的基本用法

編輯:關於 Android 程式設計

要用 RoboGuice,最基本的動作是透過註解宣告「這裡需要什麼」,剩下的交給框架。常用的註解有三個:

@InjectView(R.id.hello)      TextView helloLabel;
@InjectResource(R.drawable.icon)   Drawable icon;
@Inject                      LocationManager loc;

分別對應:從佈局中取出 View、從資源中取出內容、以及由 Injector 提供的服務/物件。

模組與 Injector 的關係

模組(Module)是 Guice 建構物件圖的基本單位,而實際執行建構工作的類別稱為 Injector。

在 Guice 中,模組繼承 AbstractModule;在 RoboGuice 中則繼承 AbstractAndroidModule。Injector 會參照模組裡定義的 Bindings,推導出類別與類別之間的關係圖,據此建立所需的物件。

某些情況下你可能想直接取得 Injector 來用,RoboActivity 提供了 getInjector():

Injector injector = getInjector();
LocationManager loc = injector.getInstance(LocationManager.class);

寫一個模組

以下示範把一個介面綁定到它的實作:

public class SayModule extends AbstractAndroidModule {

    @Override
    protected void configure() {
        bind(ISayService.class).to(SayHello.class);
    }
}

寫好之後,RoboGuice 需要知道這個模組的存在,才能把它載入進行解析。一旦綁定生效,任何需要 ISayService 的地方只要標上 @Inject,就會拿到 SayHello 的實例——而且測試時只要換一個模組,就能替換成 mock 實作,這正是依賴注入最大的價值。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved