标签:help 线程安全 obj 单例 div pre new 单例模式 sharp
第一种,懒汉模式,没考虑线程安全
public class Singleton { private static Singleton _instance = null; private Singleton(){} public static Singleton CreateInstance() { if(_instance == null) { _instance = new Singleton(); } return _instance; } }
第二种,经典模式
public class Singleton { private volatile static Singleton _instance = null; private static readonly object lockHelper = new object(); private Singleton(){} public static Singleton CreateInstance() { if(_instance == null) { lock(lockHelper) { if(_instance == null) _instance = new Singleton(); } } return _instance; } }
第三种,饿汉模式
public class Singleton { private Singleton(){} public static readonly Singleton instance = new Singleton(); }
标签:help 线程安全 obj 单例 div pre new 单例模式 sharp
原文地址:http://www.cnblogs.com/chenh/p/7894606.html