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

Android RoboGuice2 使用指南(2):第一個範例 Hello World

編輯:Android 開發教學

本例要實現的功能與 RoboGuice 1.x 版本的 Hello World 完全相同,差別只在改用 RoboGuice2.0 來實作。透過對照,你能清楚看到兩代之間的變化。

準備工作

RoboGuice 2.0 由四個 jar 檔組成:

可從 https://code.google.com/p/roboguice/ 下載。

建立一個新的 Android 專案(例如 GuiceDemo),目標平台選 Android 1.5 以上。

在專案下建立一個 libs 目錄,把 jar 檔複製進去,然後透過 Project → Properties → Java Build Path → Libraries → Add JARs 加入參照。

注意:從 ADT 17 開始,加入的 jar 檔必須放在 libs 子目錄下。

2.0 最重要的變化:不再需要 RoboApplication

RoboGuice2 中已經不再包含 RoboApplication 類,因此無需也不可能派生它的子類。這是升級時最直觀的差異。

版面配置

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView
        android:id="@+id/hello"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

</LinearLayout>

這裡定義了一個 id 為 hello 的 TextView。

相依注入的核心原則

假設這個應用使用一個 IGreetingService,它有個 getGreeting() 方法回傳字串。至於 IGreetingService 由誰實作,GuiceDemo 完全不關心。

相依注入設計模式的核心原則是:Separate behavior from dependency resolution——把「應用要實現的功能」與「它依賴的服務或其他物件」分離開來。

對本例來說,GuiceDemo 只知道它依賴 IGreetingService 這個服務,至於具體實作者是誰,它不需要也不應該知道。在 RoboGuice 中,用 @Inject 來表達這種依賴關係。

Activity 程式碼

public class GuiceDemo extends RoboActivity {

    @InjectView(R.id.hello) TextView helloLabel;
    @Inject IGreetingService greetingServce;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        helloLabel.setText(greetingServce.getGreetings());
    }
}

三個關鍵點:

使用 RoboGuice 的 Activity 必須從 RoboActivity 派生(它是 Activity 的子類)。

@Inject 標註 greetingServce 依賴於 IGreetingService 服務。

@InjectView 表示 helloLabel 依賴於 XML 中的 R.id.hello。

注意程式碼中沒有建立 greetingServce 物件的程式碼(例如 new XXX()),也沒有為 helloLabel 賦值。這些都由 RoboGuice 自動建立並注入。

兩個實作版本

為了示範切換實作的容易程度,我們準備兩個實作:

public class HelloChina implements IGreetingService {
    @Override
    public String getGreetings() {
        return "Hello,China";
    }
}

public class HelloWorld implements IGreetingService {
    @Override
    public String getGreetings() {
        return "Hello,World";
    }
}

這個範例真正想傳達的事

切換 HelloWorld 與 HelloChina,你完全不需要改動 GuiceDemo 的任何一行程式碼——只要調整綁定設定即可。

這正是相依注入的價值所在:把「用什麼」與「怎麼用」解耦。在沒有 DI 的情況下,一旦要換實作,你就得搜尋所有 new HelloWorld() 的地方逐一替換;有了 DI,切換只是一個設定檔的改動。

這個特性在寫單元測試時尤其可觀——把真實服務換成 Mock 實作,測試就能在不啟動網路、不連資料庫的情況下運行。

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