by sebastianavina · 15y ago · 0 comments
public class Singleton {
private static Singleton self = null;
private Singleton() {
//...
}
public static Singleton getInstance() {
if(self == null) {
self = new Singleton();
}
return self;
}
...
}
So at any point in your code you can call Singleton.getInstance() to have access to the same Singleton object. So it's effectively the same thing as a global variable.Edit: Added `static' to be more correct.
It has to be:
private static Singleton self = null;
public enum Singleton {
INSTANCE;
}
Guaranteed against multiple instantiation.Edit: the class version of the singleton example should also be made final, or I could just extend your class and therefore bypass your singleton restriction.
The only reason to use a singleton over static members is that it feels like OO. I suppose it also makes it easier to replace the singleton with a 'multiton' at some point in the future which somewhat justifies it.
it's surprisingly tricky to get lazy init right.
"a design pattern [that restricts] the instantiation of a class to one object"