温馨提示×

C#类的单例模式实现

c#
小樊
85
2024-08-11 23:51:41
栏目: 编程语言

在C#中,可以使用静态变量和私有构造函数来实现单例模式。以下是一个简单的示例:

public class Singleton
{
    private static Singleton instance;

    // 私有构造函数,防止外部实例化
    private Singleton()
    {
    }

    // 获取单例实例
    public static Singleton GetInstance()
    {
        if (instance == null)
        {
            instance = new Singleton();
        }
        return instance;
    }
}

在上面的示例中,通过私有构造函数防止外部实例化,通过静态变量和GetInstance方法来获取单例实例。在调用GetInstance方法时,如果实例为空,则创建一个新的实例并返回;否则直接返回已存在的实例。这样就保证了整个应用程序中只有一个实例存在。

另外,也可以使用Lazy类来实现延迟加载的单例模式:

public class Singleton
{
    private static readonly Lazy<Singleton> instance = new Lazy<Singleton>(() => new Singleton());

    private Singleton()
    {
    }

    public static Singleton GetInstance()
    {
        return instance.Value;
    }
}

使用Lazy类可以更方便地实现延迟加载,只有在第一次调用GetInstance方法时才会创建实例。

0