Sunday, July 20, 2008

Initialize on Demand Holder Class & Singleton

public class S {
private S() {}

private static class SHolder {
private static S s = new S();
}//End of Class SHolder

public static S getInstance() {
return SHolder.s;
}//End of getInstance

}//End of class S


Description:
The reason you need the inner class to hold the instance is if you have other static methods you want to be able to call without creating the singleton instance.

Static members are created when the class is first used, so calling another static method causes all static data (including the instance variable) to be initialized. By putting it in an inner class, only when the inner class is first referenced (which should only be during calls to the outer class's getInstance()) does the instance get created.

Basically the static inner class is slightly more lazy, but you'll only notice the difference if there are other static methods on your singleton class that are called before getInstance(). In general, I'd say it's bad practice to do that (static methods other than getInstance() on a singleton), but I guess some people must do that.

0 Comments:

Post a Comment

<< Home