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;
it's surprisingly tricky to get lazy init right.
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.
In Java/C# you can use a nested class to ensure thread safety and cheat towards having your static methods. For example:
private int Foo() { }
public static int Foo() { return _instance.Foo(); }
private static FooBar _instance { return Nested.instance; }
FooBar() { // Initialize here! }
class Nested {
static Nested() { }
internal static readonly FooBar instance = new FooBar();
}
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.
"a design pattern [that restricts] the instantiation of a class to one object"