鍍金池/ 教程/ Android/ Scopes
Just-in-time Bindings
Binding Annotations
Standard Injection
第一個(gè)例子 Hello World
Bindings 概述
Linked Bindings
如何綁定 generic 類型
@Provides Methods
RoboGuice 功能描述
概述
綜合示例 Astroboy
Inject Resources
Instance Bindings
Inject 自定義 View
Scopes
Provider Bindings
Untargetted Bindings
Inject Extra
第一個(gè)例子 Hello World
Inject Context
發(fā)送接收 Events
Inject View

Scopes

缺省情況下,Guice 每次都創(chuàng)建類的一個(gè)新的實(shí)例對(duì)象給需要該類實(shí)例的地方??梢允褂?Scopes 來(lái)修改這個(gè)缺省行為,Scope 允許在一定范圍內(nèi)重用類實(shí)例。Roboguice 中常用的有兩種:

  • @Singleton 整個(gè) Application 生命周期中使用同一實(shí)例對(duì)象
  • @ContextScoped 同一個(gè)Context(如 Activity)中共享某一實(shí)例對(duì)象。

使用 Scope 的方法為使用相應(yīng)的標(biāo)記,如:

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

或者在 Module 中使用 bind 語(yǔ)句:

bind(TransactionLog.class)
 .to(InMemoryTransactionLog.class)
 .in(Singleton.class);

如果使用 @Provides,可以有:

@Provides @Singleton
TransactionLog provideTransactionLog() {
...
}

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

上一篇:@Provides Methods下一篇:Bindings 概述