Friday, May 21, 2010

Singleton refactored:Initialization on demand holder idiom...

Hey guys, check this out. I found this while searching around different styles for singleton pattern. It basically provides on demand loading of the instance.

public class Something {
 private Something() {
 } 
 private static class LazyHolder {
  private static final Something INSTANCE = new Something();
 } 
 public static Something getInstance() {
  return LazyHolder.INSTANCE;
 }
}

The static class LazyHolder is only executed when the static method getInstance is invoked on the class Something, and the first time this happens the JVM will load and initialize the LazyHolder class. The initialization of the LazyHolder class results in static variable INSTANCE being initialized by executing the (private) constructor for the outer class Something.

More @ Wiki

0 Comments: