开发者

What is the best way to implement Singleton Design Pattern in C# with performance constraint?

开发者 https://www.devze.com 2022-12-31 18:01 出处:网络
Please let me know what the best way to implement Singleton Design Pattern in C# with performance constrain开发者_Go百科t?Paraphrased from C# in Depth:

Please let me know what the best way to implement Singleton Design Pattern in C# with performance constrain开发者_Go百科t?


Paraphrased from C# in Depth: There are various different ways of implementing the singleton pattern in C#, from Not thread-safe to a fully lazily-loaded, thread-safe, simple and highly performant version.

Best version - using .NET 4's Lazy type:

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()
  {
  }
}

It's simple and performs well. It also allows you to check whether or not the instance has been created yet with the IsValueCreated property, if you need that.


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

    static Singleton() { }

    private Singleton() { }

    static public Singleton Instance
    {
        get  { return _instance; }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号