C#单例模式示例

发布时间 2023-12-28 18:52:15作者: 38874963

示例一:

public class SpiderService
{
    private static SpiderService instance;
    public static SpiderService Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new SpiderService();
            }
            return instance;
        }
    }
}

通过SpiderService.Instance访问方法。

示例二:

public sealed class Singleton
{
    private static readonly Lazy<Singleton6> lazy =
           new Lazy<Singleton>(()=> new Singleton());

    public static Singleton Instance { get { return lazy.Value; } }

    private Singleton() { }
}