Android Application Class Globals instance or static
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 co开发者_运维问答rrect.
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;
}
}
Scenario A: usage --
loc = MyApplication.getLocation();
MyApplication.setLocation(loc);
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;
}
}
Scenario B: usage --
loc = getApplication().getLocation();
getApplication().setLocation(loc);
Thank you.
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.
problems of using instance variable to maintain state
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.
I would not put them as static variables given that application class will be a singleton.
More details at this java singleton pattern, should all variables be class variables?
精彩评论