2025-02-10

缺省情況下,Guice每次都創建類的一個新的實例對象給需要該類實例的地方。可以使用Scopes來修改這個缺省行為,Scope允許在一定范圍內重用類實例。Roboguice中常用的有兩種:

@Singleton 整個Application生命周期中使用同一實例對象
@ContextScoped 同一個Context(如Activity)中共享某一實例對象。
使用Scope 的方法為使用相應的標記,如:

[java] @Singleton 
public class InMemoryTransactionLog implements TransactionLog { 
 // everything here should be threadsafe!  
 } 
@Singleton
public class InMemoryTransactionLog implements TransactionLog {
 // everything here should be threadsafe!
 }

或者在Module中使用bind 語句:

[java]bind(TransactionLog.class) 
 .to(InMemoryTransactionLog.class) 
 .in(Singleton.class); 
bind(TransactionLog.class)
 .to(InMemoryTransactionLog.class)
 .in(Singleton.class);

如果使用@Provides,可以有:

[java]@Provides @Singleton 
TransactionLog provideTransactionLog() { 
… 

@Provides @Singleton
TransactionLog provideTransactionLog() {

}

如果某個類型使用某個你不想使用的Scope標記,可以將其綁定到Scopes.NO_SCOPE取消這個Scope定義。

 

摘自 引路蜂移動軟件

發佈留言

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