Singleton points:
First, only one instance of a class;
Second, it must create an instance of itself;
Third, it must provide their own this example the entire system.
From the specific implementation point of view, it is the following three points:
One class singletons only provides a private constructor;
The second is a static class definition contains a private object class;
Third, the class provides a static public function used to create or acquire a static private object itself.
(Creation is called, the thread-safe) lazy mode
. 1 /// <Summary> 2 /// the lazy Singleton pattern (thread-safe to create multiple instances may be optimized) . 3 /// </ Summary> . 4 class the Singleton . 5 { . 6 Private static the Singleton _instance = null ; . 7 . 8 Private static Object _lock = new new Object (); . 9 10 Private the Singleton () . 11 { 12 is Console.WriteLine ( " created " ); 13 } 14 15 public static Singleton GetInstance () 16 { 17 Console.WriteLine ( " Loading " ); 18 19 IF (_instance == null ) // double-threaded locking solve security problems 20 { 21 Lock (_lock) 22 { 23 IF (_instance == null ) 24 { 25 return _instance = new new the Singleton (); 26 is } 27 } 28 29 } 30 31 return _instance; 32 }
transfer
static void Main(string[] args) { HashSet<string> vs = new HashSet<string>(); Console.WriteLine("lazy"); TaskFactory taskFactory = new TaskFactory(); List<Task> tasks = new List<Task>(); Thread.Sleep(5000); for (int i = 0; i < 5; i++) { tasks.Add(taskFactory.StartNew(() => { Singleton temp = Singleton.GetInstance(); vs.Add(temp.ToString()); })); } Thread.Sleep(5000); Console.WriteLine(vs.Count); Console.Read(); }
Instance is created multiple times before optimization
Optimized
Starving mode
1 /// <summary> 2 /// EagerPattern 先创建实例 线程安全 耗内存 效率变低 3 /// </summary> 4 class EagerSingleton 5 { 6 private readonly static EagerSingleton _instance = new EagerSingleton(); 7 private EagerSingleton() 8 { 9 } 10 public EagerSingleton GetInstance() 11 { 12 return _instance; 13 } 14 }
在这种模式下,无需自己解决线程安全性问题,CLR会给我们解决。这个类被加载时,会自动实例化这个类。但是不管用不用,都会先实例化。