Double-Checked Locking
public class Singleton { private volatile static Singleton _instance = null; private static readonly object _locker = new object(); private Singleton() { } public static Singleton GetInstance() { if (_instance == null) { lock (_locker) { if (_instance == null) _instance = new Singleton(); } } return _instance; } }
静态初始化
public sealed class Singleton { private static readonly Singleton _instance = new Singleton(); // 显示静态构造函数,告诉C#编译器不要将Type标记beforefieldinit(这样就能够使程序在类的字段被引用时才会实例化) static Singleton() { } // 防止创建该类的默认实例 private Singleton() { } public static Singleton Instance { get { return _instance; } } }
延迟初始化
public sealed class Singleton { private Singleton() { } public static Singleton Instance { get { return Nested._instance; } } private class Nested { static Nested() { } internal static readonly Singleton _instance = new Singleton(); } }
.Net 4's Lazy<T> type
public sealed class Singleton { private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton()); private Singleton() { } public static Singleton Instance { get { return lazy.Value; } } }
以上4中方式都是线程安全的单例实现代码,推荐使用Lazy<T>的方式简单且性能良好。