在 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)这段代码是静态初始化
/// <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()
{
}
}