Android中的单子与应用上下文?[英] Singletons vs. Application Context in Android?



回顾这篇帖子列举了使用单例的几个问题并且已经看到了几个使用单例模式的 Android 应用程序示例,我想知道使用单例而不是通过全局应用程序状态共享的单个实例是否是一个好主意(子类化 android.os.Application 并通过 context.getApplication() 获取它).


说实话,我希望在这篇文章中得到相同的答案 带有 Web 应用程序的单例模式,不是一个好主意! 但适用于 Android.我对么?DalvikVM 有什么不同?


  • 同步
  • 可重用性
  • 测试


我非常不同意 Dianne Hackborn 的回应.我们一点一点地从我们的项目中删除所有单例,以支持轻量级、任务范围的对象,这些对象可以在您实际需要时轻松地重新创建.

单例是测试的噩梦,如果延迟初始化,将引入带有微妙副作用的"状态不确定性"(当将 getInstance() 的调用从一个范围转移到另一个范围时,可能会突然出现).可见性是另一个问题,由于单例意味着对共享状态的"全局"(=随机)访问,因此在并发应用程序中未正确同步时可能会出现细微的错误.





Recalling this post enumerating several problems of using singletons and having seen several examples of Android applications using singleton pattern, I wonder if it's a good idea to use Singletons instead of single instances shared through global application state (subclassing android.os.Application and obtaining it through context.getApplication()).

What advantages/drawbacks would both mechanisms have?

To be honest, I expect the same answer in this post Singleton pattern with Web application, Not a good idea! but applied to Android. Am I correct? What's different in DalvikVM otherwise?

EDIT: I would like to have opinions on several aspects involved:

  • Synchronization
  • Reusability
  • Testing


I very much disagree with Dianne Hackborn's response. We are bit by bit removing all singletons from our project in favor of lightweight, task scoped objects which can easiliy be re-created when you actually need them.

Singletons are a nightmare for testing and, if lazily initialized, will introduce "state indeterminism" with subtle side effects (which may suddenly surface when moving calls to getInstance() from one scope to another). Visibility has been mentioned as another problem, and since singletons imply "global" (= random) access to shared state, subtle bugs may arise when not properly synchronized in concurrent applications.

I consider it an anti-pattern, it's a bad object-oriented style that essentially amounts to maintaining global state.

To come back to your question: Although the app context can be considered a singleton itself, it is framework-managed and has a well defined life-cycle, scope, and access path. Hence I believe that if you do need to manage app-global state, it should go here, nowhere else. For anything else, rethink if you really need a singleton object, or if it would also be possible to rewrite your singleton class to instead instantiate small, short-lived objects that perform the task at hand.