An immutable object is initialized by its constuctor only, while a singleton is instantiated by a static method. How to make an immutable singleton in Java?
The solution pointed out by Sean is a good way of initializing singletons if their creation is not expensive. If you want to "lazy loading" capability, look into the initialization on demand holder idiom.
// from wikipedia entry
public class Singleton {
// Private constructor prevents instantiation from other classes
private Singleton() {
}
/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class SingletonHolder {
public static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}