Android RoboGuice 使用指南(11): Scopes

jerry Android 2015年08月24日 收藏

缺省情况下,Guice每次都创建类的一个新的实例对象给需要该类实例的地方。可以使用Scopes来修改这个缺省行为,Scope允许在一定范围内重用类实例。Roboguice中常用的有两种:

  • @Singleton 整个Application生命周期中使用同一实例对象
  • @ContextScoped 同一个Context(如Activity)中共享某一实例对象。

使用Scope 的方法为使用相应的标记,如:

  1. @Singleton
  2. public class InMemoryTransactionLog implements TransactionLog {
  3. // everything here should be threadsafe!
  4. }

或者在Module中使用bind 语句:

  1. bind(TransactionLog.class)
  2. .to(InMemoryTransactionLog.class)
  3. .in(Singleton.class);

如果使用@Provides,可以有:

  1. @Provides @Singleton
  2. TransactionLog provideTransactionLog() {
  3. ...
  4. }

如果某个类型使用某个你不想使用的Scope标记,可以将其绑定到Scopes.NO_SCOPE取消这个Scope定义。