单例用于确保仅创建对象的一个实例。单例仅允许创建其自身的单个实例,这意味着它将控制其创建。单例是“四人帮”设计模式之一,是一种创造模式。
public sealed class Singleton { private static Singleton _instance; private static object _lock = new object(); private Singleton() { } public static Singleton GetSingleton() { if (_instance == null) { CreateSingleton(); } return _instance; } private static void CreateSingleton() { lock (_lock ) { if (_instance == null) { _instance = new Singleton(); } } } }
Jon Skeet为惰性,线程安全的单例提供以下实现:
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() { } }