三种单例模式写法:
public class Singleton { private static Singleton instance; private static readonly object syncRoot = new object(); private Singleton() { } public static Singleton GetInstance() { if (instance == null)//Double-Check Locking 双重锁定,比直接lock性能更好,最完美的模式(懒汉式单例) { lock (syncRoot) { if (instance == null) { instance = new Singleton(); } } } return instance; } } public class Singleton1 { private static Singleton1 instance; private static readonly object syncRoot = new object(); private Singleton1() { } public static Singleton1 GetInstance() { lock (syncRoot)//每次调用GetInstance都需要lock,影响性能(懒汉式单例) { if (instance == null) { instance = new Singleton1(); } } return instance; } } public class Singleton2 { private static Singleton2 instance=new Singleton2();//静态初始化方式(饿汉式单例),类一加载就实例化对象,一般这样用也没问题,缺点:提前占用系统资源 private Singleton2() { } public static Singleton2 GetInstance() { return instance; } }
双重锁定性能优化分析: