单例模式:简单来说,就是指类只能被初始化一次, 一般情况下单例类是sealed
单例模式的四种实现方式:
- 线程安全的创建对象的形式
public sealed class Singleton { private static Singleton _singleton = null; private static object Singleton_Lock = new object(); public static Singleton CreateInstance() { if (_singleton==null) { lock (Singleton_Lock) { if (_singleton==null) { _singleton = new Singleton(); } } } return _singleton; } } 双重if+锁的机制,保证线程安全,且只被实例化一次 
- 静态属性形式
public sealed class Singleton { private Singleton() { } private static readonly Singleton _singletonInstance = new Singleton(); public static Singleton GetInstance { get { return _singletonInstance; } } } 由CLR保证,在程序第一次使用该类之前被调用,而且只调用一次 
- 静态构造函数形式
public sealed class Singleton { private static Singleton _singleton = null; static Singleton() { _singleton = new Singleton(); } public static Singleton CreateSingleton() { return _singleton; } } 同样是由CLR保证,在程序第一次使用该类之前被调用,而且只调用一次。同静态变量一样, 它会随着程序运行, 就被实例化, 同静态变量一个道理。 
- 懒加载的形式
public sealed class Singleton { private Singleton() { } private static readonly Lazy<Singleton> lazySingleton = new Lazy<Singleton>(() => new Singleton()); public static Singleton GetInstance { get { return lazySingleton.Value; } } } 作为 .NET Framework 4.0 的一部分引入的惰性关键字为惰性初始化(即按需对象初始化)提供了内置支持。如果要使对象(如 Singleton)以延迟初始化,则只需将对象的类型(单例)传递给lazy 关键字 
本文来自博客园,作者:菜鸟小辛,转载请注明原文链接:https://www.cnblogs.com/hashxin/p/15528297.html
 
                    
                     
                    
                 
                    
                 
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号