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

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

问题描述

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

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

说实话,我希望在这篇文章中得到相同的答案 带有 Web 应用程序的单例模式,不是一个好主意! 但适用于 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天全站免登陆