


Definition: The singleton pattern ensures that a class has at most one instance and that there is a global point of access to it.
Usage: Use singleton whenever you need exactly one instance of a class. Also, a class containing only static methods may be considered a singleton in some cases.
class Singleton {
public static Singleton getInstance() {
if(uniqueInstance == null) {
synchronized(Singleton.class) {
if(uniqueInstance == null)
uniqueInstance = new Singleton();
}
}
}
private Singleton() {}
private volatile static Singleton uniqueInstance;
}
Note that this getInstance method won't work on Java 1.4 or earlier because the volatile keyword didn't work properly.
Copyright (C) 2008 Steven Fletcher. All rights reserved.