Reputation: 4652
I was going through a talk on singletons. To begin with, here some code:
class AppSettings {
private static AppSettings instance = new AppSettings();
private Object state1;
private Object state2;
private Object state3;
private AppSettings() {}
public static AppSettings getInstance() {
return instance;
}
}
The speaker says that since instance
is static, it is a global variable and whatever is accessible using instance
will also have global state.
Can someone explain to me what global state means? I know that global state is accessible throughout the application, and can be changed by another objects which is bad. But how does declaring instance
as static
make it global?
Upvotes: 1
Views: 472
Reputation: 43788
"global" is the wrong term for that. The variable instance
is still only visible inside the AppSettings
class. However the AppSettings
instance referenced by it is made available to the outside world via the getInstance
method.
Upvotes: 2
Reputation: 304
As there will be only one instance of the AppSettings object (as it is a static variable), the state member fields which can be accessed through this instance by any other object (Of course you need getters and setters for these members as they are private). Hence they can be used for maintaining global states
Upvotes: 1