在 class 的唯一现有构造函数中创建对 "this" 的引用

Creating a reference to "this" in the only existing constructor of a class

我的一个朋友向我展示了他对单例模式的实现。从我目前的测试来看,它似乎工作正常。我不知道为什么,但如下所示引用 "this",对我来说似乎是不好的做法。

"this" 在构造函数中的这种用法合法吗?

public class Singleton {
    private static Singleton unique = null;

    private Singleton() { unique = this; }

    public static Singleton instance() {
        if (unique == null)
            new Singleton();
        return unique;
    }
}

与通常的方法相比,是否存在显着差异:

public class Singleton {
    private static Singleton unique = null;

    private Singleton() { }

    public static Singleton instance() {
        if (unique == null)
            unique = new Singleton();
        return unique;
    }
}

我找不到任何合理的答案来解决我的问题。

所以,提前致谢!

Is this usage of "this" in the constructor legitimate?

它会起作用,但不合理且几乎不可读。感觉更像是代码的味道。

Is there even a significant difference, compared to doing it the usual way?

应始终考虑可读性和可维护性。模拟 and/or 使用这个单例会更难,因为它的实现类型 unique.

另外,正如评论中指出的那样。 None 个示例是 thread-safe。意味着这不是 true 单例。

如果你想要一个 thread-safe 具有惰性初始化的单例,我建议按如下方式实现它:

public class Singleton {

private static Singleton unique = null;

private Singleton() {
}

public static synchronized Singleton getInstance() {
    if (unique == null) {
        unique = new Singleton();
    }
    return unique;
}
}

您可以通过引入双重检查锁定来增强它:

public static synchronized Singleton getInstance() {
    if (unique == null) {
        synchronized (Singleton.class) {
            if (unique == null) {  
                unique = new Singleton();
            }
        }
    }
    return unique;
}

附加信息

有多种实现单例模式的方法:

https://www.geeksforgeeks.org/java-singleton-design-pattern-practices-examples/