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.
Sunday, July 20, 2008
Previous Posts
- Vitamins Chart
- Tongue TwistersPeter bought a butter,The butter Pe...
- Just For Laugh.... * Wife: Darling today is our a...
- Basic Doubts in Java & in Databases ? Ask Mr.Nagz....
- HTTP Header from a web site using TELNET You can ...
- When the end of the world arrives how will the med...
- 1-800-PSYCH............ Hello, Welcome to the Ps...
- Bizarre facts .. but true. 1. Coca-Cola was origi...
- Cool Ones......njoy. 1.A foolish man tells a wom...
- Validations in Javascript Email Validations if ...

0 Comments:
Post a Comment
<< Home