2025-02-10

一個應用中類於類之間的依賴關系可能非常復雜,創建於個類實例,需要先創建類所依賴的類的示例,而創建所依賴類的實例,這些類又可能依賴其它類,以此類推。因此在創建一個類實例時,你正在需要創建的是一個對象圖對象(Object Graph)。
手工創建Object Graph 是一個非常繁瑣而且容易出錯的過程,並且很難對代碼進行測試,而Guice或Roboguice可以幫助你創建Object Graph,所要做的工作是配置類和類之間的依賴關系。
模塊(Modules) 是Guice 構造Object Graph 的基本構造塊,Guice中構造object Graph 的工作有被稱為”Injector”的類來完成。
Guice在模塊為AbstractMoudule 的子類,而RoboGuice在模塊為AbstractAndroidModule的子類。RoboGuice利用 Injector 來創建所依賴的對象,而Injector 為參照Module 中定義的Bindings來構造類於類之間的關系圖。
打個比方,如果你熟悉make file 或是其它Build 系統(如 wix) 。你使用makefile 定義好需編譯的對象所依賴的源碼文件,這些源碼由可能依賴其它庫或頭文件等。makefile 定義的這些依賴關系對應到Roboguice 中為模塊中定義的bindings 。
使用make 編譯某個目標程序 (Target), make 會查看makefile 中的依賴關系,依次先編譯被依賴的對象直到最終編譯Target。對應到Roboguide(Guice)為Injector 創建某個對象,它會根據定義的Bindings 首先創建那些被依賴的對象,直到創建所需對象。
在HelloWorld例子中,我們沒有看到Injector的直接使用,這是因為RoboGuice 替我們調用瞭Injector來創建IGreetingService對象。
如果在某些情況下,如果你想直接使用Injector ,可以使用RoboActivity 的getInjector().
比如修改GuiceDemo,去掉@Inject IGreetingService greetingServce 而使用Injector的getInstance 來創建IGreetingService 實例。
[java]
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); 
  
 Injector injector=getInjector(); 
 IGreetingService greetingServce 
 =injector.getInstance(IGreetingService.class); 
 helloLabel.setText(greetingServce.getGreetings()); 
 } 
  

Module中的還是綁定到HelloChina.
[java]
public class GreetingModule extends AbstractAndroidModule{ 
  
 @Override 
 protected void configure() { 
 //bind(IGreetingService.class).to(HelloWorld.class); 
 bind(IGreetingService.class).to(HelloChina.class); 
  
 } 
  

Injector 的工作就是構造Object Graph,當你調用getInstance 來構造某個類型的對象時,Injector 會自動根據類之間的依賴關系創建所需類的實例。
定義類之間的依賴關系的方法是通過擴展AbstractAndroidModule,重載其configure方法。在configure方法中定義各種Bindings。這些方法同時也做類型檢測,如果使用的類型不正確,編譯器將給出錯誤。
綁定Bindings 可以有下面幾種類型:
Linked bindings
instance bindings
@provider methods
provider bindings
constructor bindings
untargetted bindings
built-in bindings
just-in-time bindings
providers 等
後面就逐個介紹這些bindings ,這些bindings 是通用的和Android平臺相關性不大,可以同時用於Java EE ,Java SE 平臺,RoboGuice 提供瞭於Android平臺相關的dependency injector ,後面也有詳細介紹。

摘自 引路蜂移動軟件

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *