Android RoboGuice使用指南(11):Scopes
2296 点击·0 回帖
![]() | ![]() | |
![]() | 缺省情况下,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定义。 | |
![]() | ![]() |