Should a singleton in Java use static variables or member variables? Are there any advantages to either?
Singleton implementation can either have static members or instance members. Static classes can contain static members only. It can implement any other interface or base class is required. It cannot implement the interface or any other base class.
The Singleton class does not require you to use the static keyword everywhere. Static class objects cannot be passed as parameters to other methods whereas we can pass instances of a singleton as a parameter to another method.
A common mistake with that implementation is to neglect synchronization, which can lead to multiple instances of the singleton class.
If it would have been instance method , you would have needed an object to call getInstance. Now there is no way to create an object of class SingleObject outside the class (since constructor is private ) & this is the real trouble. Conclusion 1: This means we need to have a static method.
You should use member variables. A singleton is an object (i.e. an instance of a class) and so should be modelled as such; even if you only ever intend to create one of them.
Statics should be used for class level variables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With