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

时间:2010-05-25 06:00:40

标签: design-patterns

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

3 个答案:

答案 0 :(得分:4)

C# in Depth转述: 在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()
  {
  }
}

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

答案 1 :(得分:2)

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

    static Singleton() { }

    private Singleton() { }

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

答案 2 :(得分:1)

直到最近,我才知道Singleton被许多人认为是反模式,应该避免。清洁解决方案可以是使用DI或其他功能。即使你和单身人士一起去阅读这个有趣的讨论 What is so bad about singletons?

相关问题