在 Android 中使用静态变量 [英] Using static variables in Android
问题描述
在 android 中,是否推荐使用静态变量?例如,在 Java 中实现单例模式,我通常会这样做:
In android, are using static variables a recommended practice? E.g, implementing a Singleton pattern in Java, I usually do:
private static A the_instance;
public static A getInstance() {
if (the_instance == null) {
the_instance = new A();
}
return the_instance;
}
此外,Android JVM 何时会清除这些内容?
Also, when does this get cleaned up by the Android JVM?
推荐答案
static
字段作为一个整体附加到 Class
实例,而后者又附加到ClassLoader
加载类.当整个 ClassLoader
被回收时,the_instance
将被卸载.我 90% 确定当 Android 销毁应用时会发生这种情况(不是当它进入后台或暂停时,而是完全关闭时.)
static
fields are attached to the Class
instance as a whole, which is in turn attached to the ClassLoader
which loaded the class. the_instance
would be unloaded when the entire ClassLoader
is reclaimed. I am 90% sure this happens when Android destroys the app (not when it goes into the background, or pauses, but is completely shut down.)
因此,只要您的应用运行,就可以将其视为存在.单身人士是个好主意吗?人们有不同的看法.我个人认为使用得当就好.我认为答案在 Android 上没有太大变化.内存使用本身不是问题;如果你需要在内存中加载一堆东西,那要么是一个问题,要么不是,不管你是否将数据封装在一个单例中.
So, think of it as living as long as your app runs. Is Singleton a good idea? People have different views. I think it's fine when used appropriately, myself. I don't think the answer changes much on Android. Memory usage isn't the issue per se; if you need to load a bunch of stuff in memory, that's either a problem or it isn't, regardless of whether you encapsulate the data in a Singleton.
这篇关于在 Android 中使用静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!