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

查看:116
本文介绍了单机与Android中的应用程序上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



这两种机制有什么优点/缺点?



说实话,我期待同样的答案发布使用Web应用程序的单例模式,不是一个好主意! a>但应用于Android。我对么?否则,DalvikVM有什么不同?



编辑:我想对涉及的几个方面提出意见:




  • 同步

  • 可重用性

  • 测试


解决方案

我非常不同意Dianne Hackborn的回应。我们从我们的项目中逐一删除所有单身人士,倾向于轻量级的任务范围对象,当您实际需要时可以轻松重新创建。



单身人士噩梦的测试,如果懒惰初始化,将引入状态不确定与微妙的副作用(可能会突然表现,当从一个范围调用getInstance()到另一个范围)。可见性被提及为另一个问题,由于单例意味着全局(=随机)访问共享状态,当并发应用程序中未正确同步时,可能会出现微妙的错误。



我认为它是一个反模式,这是一个不好的面向对象的风格,基本上相当于维持全球的状态。



回到你的问题:
虽然应用程序上下文可以被认为是一个单例本身,但是它是框架管理的,并且具有明确的生命周期,范围和访问路径。因此,我相信,如果你需要管理应用程序全局状态,那么它应该在这里,而不在其他地方。对于其他任何事情,如果你真的需要一个单例对象,或者如果还可以重写单例类,而不是实现执行手头任务的小型,短命的对象,那就重新考虑一下。 p>

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.

这篇关于单机与Android中的应用程序上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆