Well, this is my first essay, which starts from the simplest single example mode and records my growth step by step.
Singleton pattern is one of the most common design patterns, which can be found almost everywhere in project code. The purpose of this design pattern is to ensure that only one instance can exist. The single mode can be further subdivided into lazy mode and hungry mode. Let's look at them one by one.
1. Hungry man mode
It is thread safe to instantiate a class when it is loaded.
1 public class Singleton 2 { 3 //Complete instantiation when class is loaded 4 private static Singleton instance = new Singleton(); 5 6 private Singleton() 7 { 8 } 9 10 //Direct return to instance 11 public static Singleton Instance 12 { 13 get 14 { 15 return instance; 16 } 17 } 18 }
2. Lazy mode
The lazy pattern does not create an Instance when the class is loaded, but only when it is used for the first time. However, this method is not thread safe. If multiple threads call Instance at the same time, multiple instances will be created, which violates the original intention of the single Instance mode.
1 public class Singleton 2 { 3 // Don't create instance directly when class is loaded 4 private static Singleton instance; 5 6 private Singleton() 7 { 8 9 } 10 11 public static Singleton Instance 12 { 13 get 14 { 15 if (instance == null) 16 { 17 //Create an instance the first time you use it 18 instance = new Singleton(); 19 } 20 21 return instance; 22 } 23 } 24 }
3. Thread safe lazy mode
How to ensure thread safety while implementing lazy mode? The simplest way is to lock it out of if judgment.
1 public class Singleton 2 { 3 private static Singleton instance; 4 5 private static readonly object locker = new object(); 6 7 private Singleton() 8 { 9 10 } 11 12 public static Singleton Instance 13 { 14 get 15 { 16 //Lock up 17 lock (locker) 18 { 19 if (instance == null) 20 { 21 instance = new Singleton(); 22 } 23 } 24 25 return instance; 26 } 27 } 28 }
But this method needs to be locked before each access, which will affect the performance of multithreading, so we have a double check lock.
4. Double inspection lock
We only need to make if judgment again before locking, and we will not need to lock every time we visit.
1 public class Singleton 2 { 3 private static Singleton instance; 4 5 private static readonly object locker = new object(); 6 7 private Singleton() 8 { 9 10 } 11 12 public static Singleton Instance 13 { 14 get 15 { 16 if (instance == null) 17 { 18 lock (locker) 19 { 20 if (instance == null) 21 { 22 instance = new Singleton(); 23 } 24 } 25 } 26 27 return instance; 28 } 29 } 30 }