在类的唯一现有构造函数中创建对“ this”的引用

时间:2019-06-30 22:21:56

标签: java constructor singleton this keyword

我的一个朋友向我展示了这是他对单例模式的实现。从到目前为止的测试来看,它似乎工作正常。我不知道为什么,但是在我看来,引用如下所示的“ 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;
    }
}

我无法找到对我的问题的任何合理答案。

所以,先谢谢!

1 个答案:

答案 0 :(得分:0)

  

在构造函数中使用“ this”是否合法?

它可以工作,但是不合理且几乎不可读。感觉更像是代码气味。

  

与通常的方法相比,是否还有显着差异?

应始终考虑可读性和可维护性。

较难模拟和/或使用此单例,以使其实现为 unique

此外,如评论中所指出。这些示例都不是线程安全的。表示这不是 true 单例。

如果您要使用延迟初始化的线程安全单例,建议您按以下方式实现它:

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;
}

其他信息

有多种实现Singleton模式的方法:

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