问题描述
我使用的是android.app.Application类(子类)来存储一些全球性的信息。一个例子是用户位置,我们从GPS /无线抓住它的最后一次。我的问题是我是否应该存储这些全局静态变量或实例变量。不知道哪种方案是更好或更正确。
I am using the android.app.Application class (a subclass) to store some "global" information. An example is the user location the last time we grabbed it from the GPS/wifi. My question is whether I should be storing these "globals" as static variables or instance variables. Not sure which scenario is better or more correct.
方案A:使用静态变量 -
Scenario A: using static variables --
public class MyApplication extends android.app.Application {
private static Location myLocation;
public static Location getLocation() {
return myLocation;
}
public static void setLocation(Location loc) {
myLocation = loc;
}
}
方案A:使用 -
Scenario A: usage --
loc = MyApplication.getLocation();
MyApplication.setLocation(loc);
方案B:使用实例变量 -
Scenario B: using instance variables --
public class MyApplication extends Application {
private Location myLocation;
public Location getLocation() {
return this.myLocation;
}
public void setLocation(Location loc) {
this.myLocation = loc;
}
}
方案B:使用 -
Scenario B: usage --
loc = getApplication().getLocation();
getApplication().setLocation(loc);
感谢你。
推荐答案
使用静态
变量是正确的方式永远的,因为它在一个国家要维护无处不在。但为什么承担风险,当你有像共享preference()
在Java提供的,这是比较安全的,你总是可以肯定它。并得到它无处不在您的应用程序。通常保持可变的状态是一个高风险的工作。
Using Static
variable is the right way always, since its the single state you want to maintain everywhere. But why taking risk when you have something like SharedPreference()
provided by java, which is more secure and you can always be sure about it. and get it everywhere across your your application. usually maintaining states of variable is a risky task.
使用实例变量保持状态的问题。
实例变量是不同的对象不同/实例创建(所以它们被称为实例变量),所以如果通过创建一个新的对象来获取变量的值,它会返回一些你不想要的(因为它是在另一个实例中设置),在这里,如果你使用静态变量
每个实例/对象是指同一个变量(我的意思是说同一个内存位置),所以什么都改变是由做任何情况下,通过反映出来的应用程序,简化版,无论你如何访问它。
Instance variables are different for different objects/Instance you create (So they are called instance variable) so if try to get a value of the variable by creating a new object, it returns something you don't want (since it was set in another instance), where as if you use static variable
every instance/object refers the same variable (i mean to say same memory location) so what ever changes are made by any instance is reflected through out the application, does't matter how you access it.
这篇关于Android应用程序类全局实例或静态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!