灯火互联
管理员
管理员
  • 注册日期2011-07-27
  • 发帖数41778
  • QQ
  • 火币41290枚
  • 粉丝1086
  • 关注100
  • 终身成就奖
  • 最爱沙发
  • 忠实会员
  • 灌水天才奖
  • 贴图大师奖
  • 原创先锋奖
  • 特殊贡献奖
  • 宣传大使奖
  • 优秀斑竹奖
  • 社区明星
阅读:1672回复:0

Android RoboGuice使用指南(11):Scopes

楼主#
更多 发布于:2012-09-06 13:55


缺省情况下,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定义。


喜欢0 评分0
游客

返回顶部