java - Using private static nested class to implement Singleton -


i learning singleton pattern. learnt classic way implement create static field of singleton class type, hide constructor using private access modifier, , provide public getinstance() method.

however, thought of way of implementing without using private constructors:

public class swrapper {     private static singleton holder = new singleton();     private static class singleton{ /* implementation without private constructor*/}     public static singleton getinstance() {         return holder; } 

question: implementation work? (i think can't sure.) if does, there advantages or disadvantages using implementation?

it's singleton, it's eagerly initialized (not lazily initialized), it's not interesting. use of name holder suggests attempting initialization-on-demand holder idiom:

public class singleton {     private static class holder {         static final singleton instance = new singleton ();     }      public static singleton getinstance() {         return holder.instance;     }      private singleton () {     }     // rest of class omitted } 

which initializes singleton instance when first got (rather when class loaded), yet doesn't require special synchronization threadsafe.


Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -