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

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

问题描述

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

这两种机制都有哪些优点/缺点?

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

我想对涉及的几个方面发表意见:

  • 同步
  • 可重用性
  • 测试

解决方案

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

Singleton 是测试的噩梦,如果延迟初始化,将引入具有微妙副作用的状态不确定性"(在移动对 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.

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

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