简体   繁体   English

使用私有静态嵌套类实现Singleton

[英]Using private static nested class to implement Singleton

I am currently learning about the Singleton pattern. 我目前正在学习Singleton模式。 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. 我了解到,实现它的经典方法是创建Singleton类类型的静态字段,使用私有访问修饰符隐藏构造函数,并提供公共getInstance()方法。

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 : 您使用名称holder意味着您正在尝试按需初始化持有人惯用语

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. 因为您的Singleton课是私人的,所以这行不通。 That means you don't have access to it's members from outside SWrapper (except for those defined in Object of course). 这意味着您无权从SWrapper外部访问其成员(当然,在Object中定义的成员除外)。

public class SingletonWithHelper { 公共类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;
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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