Singleton mode:
Key points: 1. A class has only one instance; 2. The class creates the instance by itself; 3. The class provides the instance to the entire system by itself.
Code display:
namespace SingleTon { /// <summary> /// Lazy singleton, multi-thread safety/// Lazy, no instance is created when the class is loaded, so the class loading speed is fast, but the speed of obtaining the object at runtime is slow// / </summary> public class LazySingleTon { private static LazySingleTon instance = null; //Multi-thread safe private static object lockObject = new object(); private LazySingleTon() { Console.WriteLine("private LazySingleTon()"); }
public static LazySingleTon Instance { get { //No need to lock every time, improve efficiency if (instance == null) { //Multi-thread safe lock (lockObject) { if (instance == null) { return new LazySingleTon(); } } } return instance; } } }
/// <summary> /// Eager singleton /// The initialization is completed when the class is loaded, so the class loading is slow, but the speed of acquiring the object is fast. /// </summary> public class EagerSingleTon { // readonly allocated dynamic memory private static readonly EagerSingleTon instance = new EagerSingleTon();
private EagerSingleTon() { Console.WriteLine("private EagerSingleTon()"); }
public static EagerSingleTon Instance { get { return instance; } }
} class Program { static void Main(string[] args) { var lazy = LazySingleTon.Instance; var eager = EagerSingleTon.Instance; } } }
Note: Copy the code directly to vs to see it. Next time I install a Windows Live Writer plugin and insert code blocks.