在C#中使用性能约束实现Singleton Design Pattern的最佳方法是什么?

Mar*_*ood 6 design-patterns

请告诉我在C#中使用性能约束实现Singleton Design Pattern的最佳方法是什么?

Gan*_*ang 6

C# 深入转述:在C# 中实现单例模式有多种不同的方式,从非线程安全到完全延迟加载、线程安全、简单和高性能的版本。

最佳版本 - 使用 .NET 4 的 Lazy 类型:

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

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

  private Singleton()
  {
  }
}
Run Code Online (Sandbox Code Playgroud)

它很简单,性能也很好。如果需要,它还允许您使用IsValueCreated属性检查是否已创建实例。


CAR*_*OTH 2

public class Singleton 
{
    static readonly Singleton _instance = new Singleton();

    static Singleton() { }

    private Singleton() { }

    static public Singleton Instance
    {
        get  { return _instance; }
    }
}
Run Code Online (Sandbox Code Playgroud)