Frequently, I face requirements where I would like to use a singleton bean instead of creating new objects — and this happens all of the time. Beans that have no relevant state or are expensive to create lend itself to become a singleton. The conventional singleton idioms are fairly easy and go something like this:
// private constructor singleton idiom
public class PrivateConstructorSingleton {
public static final PrivateConstructorSingleton INSTANCE = new PrivateConstructorSingleton();
private PrivateConstructorSingleton() {}
}
// lazy loading singleton idiom
public static class LazyLoadingSingleton {
private LazyLoadingSingleton() {}
private static class LazyHolder {
static final LazyLoadingSingleton INSTANCE = new LazyLoadingSingleton();
}
public static LazyLoadingSingleton getInstance() {
return LazyHolder.INSTANCE;
}
}