实现Singleton设计模式[请提出建议]

本文关键字:Singleton 设计模式 实现 | 更新日期: 2023-09-27 18:06:00

任何人都能在实现Singleton设计模式的Java/C#代码片段中发现问题吗。

有人能给我找到这个片段实现中的缺陷吗?

class Singleton{
public static Singleton Instance() {
if (_instance == null)
_instance = new Singleton();
return _instance;
}
protected Singleton() {}
private static Singleton _instance = null;
}

实现Singleton设计模式[请提出建议]

它不是线程安全的

http://csharpindepth.com/Articles/General/Singleton.aspx

正如Kieren所说,它不是线程安全的。。。并且允许类从中派生,这意味着它不是真正的单例:

public class SingletonBasher : Singleton
{
}
Singleton x = Singleton.Instance();
Singleton y = new SingletonBasher();

xy是不同的引用,并且它们都不是null,这应该是无效的——这违反了单例的概念。

(是的,我也推荐我关于单例实现的文章:(

实现singleton(如Joshua Bloch的Effective Java(的更好方法是使用enum:

enum Singleton {
    INSTANCE();
    private Singleton() {
       ....
    }
}

如果你坚持你的方法,你还需要做三件事:

  • 将构造函数私有化(按照Jon Skeet的建议(
  • 使实例不稳定
  • 双重锁定Instance((
enum A { A; }

如果您在多线程环境中,两个不同的线程可能会进入If块,然后两个线程都会创建一个新实例。添加锁定:

class Singleton{
    public static Singleton Instance() {
        if (_instance == null) {
            lock(typeof(Singleton)) {
                if (_instance == null) {
                    _instance = new Singleton();
                }
            }
        }
        return _instance;
    }
    protected Singleton() {}
    private static Singleton _instance = null;
}

以上所有答案都是正确的。

在singleton设计模式中,您不应该允许其他人为singleton类创建实例。你必须拥有自己的权利。另一个实例可以向您请求singleton的实例。所以构造函数应该/必须是私有的。

在您的示例中,您将其设置为受保护的。在这种情况下,如果您扩展singleton类,则有可能从其他实例创建实例。不应提供这种可能性。

在代码片段中将构造函数设为私有,然后将其设为singleton类。

它不是线程安全的。

您可以通过预初始化以不同的方式实现:

private static Singleton _instance = new Singleton();
public static Singleton Instance()
{
    return _instance;
}

此方法是线程安全的,因为您只返回方法中的实例。