简体   繁体   中英

Using private static nested class to implement Singleton

I am currently learning about the Singleton pattern. I learnt that the classic way to implement it is to create a static field of the Singleton class type, hide the constructor using private access modifier, and provide a public getInstance() method.

However, I thought of another way of implementing it 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: Does this implementation work? (I think it does but I can't be sure.) If it does, are there any advantages or disadvantages to using this implementation?

It's a singleton, but it's eagerly initialized (not lazily initialized), so it's not that interesting. Your use of the name holder suggests you are attempting the 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 the singleton instance when first got (rather than when class is loaded), yet doesn't require any special synchronization to be threadsafe.

That won't work, since your Singleton class is private. That means you don't have access to it's members from outside SWrapper (except for those defined in Object of course).

public class SingletonWithHelper {

private SingletonWithHelper(){}

//This is the most widely used approach for Singleton class as it doesn’t
//require synchronization.
private static class SingletonHelper{
    private static final SingletonWithHelper SINGLETON = new SingletonWithHelper();
}

public static SingletonWithHelper getInstance(){
    return SingletonHelper.SINGLETON;
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM