标签:
单例模式三种写法:
第一种最简单,但没有考虑线程安全,在多线程时可能会出问题
1 public class Singleton 2 { 3 private static Singleton _instance = null; 4 private Singleton(){} 5 public static Singleton CreateInstance() 6 { 7 if(_instance == null) 8 9 { 10 _instance = new Singleton(); 11 } 12 return _instance; 13 } 14 }
第二种考虑了线程安全,不过有点烦,但绝对是正规写法,经典的一叉
1 public class Singleton 2 { 3 private volatile static Singleton _instance = null; 4 private static readonly object lockHelper = new object(); 5 private Singleton(){} 6 public static Singleton CreateInstance() 7 { 8 if(_instance == null) 9 { 10 lock(lockHelper) 11 { 12 if(_instance == null) 13 _instance = new Singleton(); 14 } 15 } 16 return _instance; 17 } 18 }
第三种可能是C#这样的高级语言特有的,实在懒得出奇
1 public class Singleton 2 { 3 4 private Singleton(){} 5 public static readonly Singleton instance = new Singleton(); 6 }
这三种 可以很容易找到
第二种写法 可以改为:
1 public class Singleton 2 { 3 private volatile static Singleton _instance = null; 4 private static readonly object lockHelper = new object(); 5 private Singleton(){} 6 public static Singleton CreateInstance() 7 { 8 if(_instance == null) 9 { 10 11 bool lockTaken = false; 12 try 13 { 14 System.Threading.Monitor.Enter(lockHelper , ref lockTaken); 15 if (_instance == null) 16 { 17 _instance = new Singleton(); 18 } 19 } 20 finally 21 { 22 if (lockTaken) 23 { 24 System.Threading.Monitor.Exit(lockHelper); 25 } 26 } 27 28 } 29 30 return _instance; 31 32 } 33 34 }
第三种 高级语言特有的实现方式 很明显的问题 无法实现延迟加载
标签:
原文地址:http://www.cnblogs.com/daidch2015/p/4800126.html