哪个单例工具更好C#

时间:2013-02-26 12:32:59

标签: c# singleton

在C#中实现单例模式有各种不同的方法。我将以优雅的相反顺序呈现它们,从最常见的,不是线程安全的,以及完全延迟加载,线程安全,简单且高性能的版本开始。

我正在谷歌“如何实现单身”并找到了3种方式,哪种单例工具更好C#?

1)此代码使用lock()

public class Singleton

{
    // Static object of the Singleton class. 
    private static volatile Singleton _instance = null;

    /// <summary>
    /// The static method to provide global access to the singleton object.
    /// </summary>
    /// <returns>Singleton object of class Singleton.</returns>
    public static Singleton Instance()
    {
        if (_instance == null)
        {
            lock (typeof(Singleton))
            {
                _instance = new Singleton();
            }
        }
        return _instance;
    }

    /// <summary>
    /// The constructor is defined private in nature to restrict access.
    /// </summary>
    private Singleton() { }

}  

2)此代码为静态init

/// <summary>
/// A sealed class providing access to it's ONLY readonly static instance.
/// </summary>
sealed class SingletonCounter 
{
    public static readonly SingletonCounter Instance = 
         new SingletonCounter();

    private SingletonCounter() {}
}

3)此代码使用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()
    {
    }
} 

1 个答案:

答案 0 :(得分:1)

除非有一个超越原因,否则你应该选择“简单”。事实上,你已经巧妙地证明了使用更具异国情调的图案可能会使它们变得混乱(例如1中至少有2个值得注意的问题)。所以你应该更喜欢2,因为它显然是正确的。它的缺点是它不是懒惰的,但由于类型上没有其他方法,你可以做的唯一有用的事情是获取实例,所以这不是问题:有从来没有这样的情况,它是懒惰的有用。它也是完全无锁的,没有条件可以评估来获取实例。