1

我刚开始使用 Roboguice (+Guice),我不确定如何使用它的最佳实践。

在我的活动中,我有大约 5 个函数(大约 30 个),它们使用一个名为“ProviderQueries”(Singleton)的对象。我可以通过两种方式使用它:

1.)

    protected void onResume() {
       super.onResume();
       getInjector().getInstance(ProviderQueries.class).setLanguage("EN");
}

2.)

class MyActivity extends RoboActivity {
    @Inject
    private ProviderQueries pv;

    ...

       protected void onResume() {
          super.onResume();
          pv.setLanguage("EN");
          }        
 }

1 - 太长,但在需要的地方使用了 ProviderQueries 的实例
2 - 短而漂亮,但“pv”可用于整个活动,但只需要在 5 个不同的功能中......

您会使用哪种方法,或者您有更好的解决方案?

提前致谢!

4

2 回答 2

1

This is a bit of a judgement call. To me, 5 functions seems justification enough to put this in a member variable, which uses a cleaner syntax and reduces the explicit dependency on the injector. I see your point about it not being used in all 30 methods, but that seems of a secondary concern in my personal opinion (your own sense of aesthetics of course may be different).

If ProviderQueries is especially memory intensive, you may want to consider going with option 2 instead of 1 since option 1 will keep the object live for the duration of the activity. Not a consideration for most objects, but could be an issue for some.

If you weren't using Guice, how would you access your singleton? Presumably through an accessor method? You can, of course, always write your own accessor that performs #2 for you in a more compact way, although it won't bypass the small reflection overhead incurred for each access to the singleton.

于 2011-08-18T11:31:39.810 回答
0

也许您需要使用 Guice 的 Provider 类。

对于来自 Guice 网站的(简化的)示例:

public class RealBillingService implements BillingService {
  private final Provider<CreditCardProcessor> processorProvider;

  @Inject
  public RealBillingService(Provider<CreditCardProcessor> processorProvider) {
    this.processorProvider = processorProvider;
  }

  public Receipt chargeOrder(PizzaOrder order, CreditCard creditCard) {
    CreditCardProcessor processor = processorProvider.get();

    /* use the processor and transaction log here */
  }
}

提供者将隐藏范围并且是轻量级的。它们可以在初始注入时保存在内存中,但不会保存对您正在使用的具体对象的引用。

这方面的文档,以及更多示例: http ://code.google.com/p/google-guice/wiki/InjectingProviders

于 2012-04-21T18:35:34.650 回答