回顾这篇文章,列举了使用单例对象的几个问题
并且已经看到了几个使用单例模式的Android应用程序的例子,我想知道使用单例而不是通过全局应用程序状态共享的单个实例是否是一个好主意(子类化Android .os. application并通过context.getApplication()获取它)。
这两种机制有什么优点/缺点?
老实说,我希望在这篇文章中得到同样的答案,单例模式与Web应用程序,不是一个好主意!但应用于Android。我说的对吗?DalvikVM有什么不同?
编辑:我想就所涉及的几个方面发表意见:
同步
可重用性
测试
My activity calls finish() (which doesn't make it finish immediately, but will do eventually) and calls Google Street Viewer. When I debug it on Eclipse, my connection to the app breaks when Street Viewer is called, which I understand as the (whole) application being closed, supposedly to free up memory (as a single activity being finished shouldn't cause this behavior). Nevertheless, I'm able to save state in a Bundle via onSaveInstanceState() and restore it in the onCreate() method of the next activity in the stack. Either by using a static singleton or subclassing Application I face the application closing and losing state (unless I save it in a Bundle). So from my experience they are the same with regards to state preservation. I noticed that the connection is lost in Android 4.1.2 and 4.2.2 but not on 4.0.7 or 3.2.4, which in my understanding suggests that the memory recovery mechanism has changed at some point.
从众所周知的马的嘴…
在开发你的应用程序时,你可能会发现有必要在整个应用程序中共享数据、上下文或服务。例如,如果你的应用程序有会话数据,比如当前登录的用户,你可能会想要公开这些信息。在Android中,解决这个问题的模式是让你的Android .app.Application实例拥有所有的全局数据,然后把你的Application实例当作一个具有各种数据和服务的静态访问器的单例。
当编写一个Android应用程序时,你保证只有一个Android .app. application类的实例,所以它是安全的(谷歌Android团队推荐)将其视为单例。也就是说,您可以安全地将静态getInstance()方法添加到应用程序实现中。像这样:
public class AndroidApplication extends Application {
private static AndroidApplication sInstance;
public static AndroidApplication getInstance(){
return sInstance;
}
@Override
public void onCreate() {
super.onCreate();
sInstance = this;
}
}