【问题标题】:What is the best way to implement Singleton Design Pattern in C# with performance constraint?在具有性能约束的 C# 中实现单例设计模式的最佳方法是什么?
【发布时间】:2010-05-25 06:00:40
【问题描述】:

请让我知道在具有性能约束的 C# 中实现单例设计模式的最佳方法是什么?

【问题讨论】:

  • 你说的“性能约束”是什么?
  • 我想要最快的实现。我听说过这个网站上的一篇文章,但不记得名字了。如果有人知道,请在此处发布。

标签: design-patterns


【解决方案1】:

转述自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 属性检查是否已创建实例。

【讨论】:

    【解决方案2】:
    public class Singleton 
    {
        static readonly Singleton _instance = new Singleton();
    
        static Singleton() { }
    
        private Singleton() { }
    
        static public Singleton Instance
        {
            get  { return _instance; }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-24
      • 1970-01-01
      • 1970-01-01
      • 2013-05-25
      • 1970-01-01
      相关资源
      最近更新 更多