Singleton ensures that a class has only one instance and provides a global access point to it.
Generally, we can make a global variable to make an object accessible, but it cannot prevent you from instantiating multiple objects. The best way is to let the class itself be responsible for saving its unique instance. This class can ensure that no other instance can be created, and it can provide a method to access the instance.
SyncRoot = (); (instance = (SyncRoot) // If the instance does not exist, a new instance is created. Otherwise, an existing instance is returned.
(Instance =
Note:
Constructor private Singleton () {}. This blocks the possibility of using new to create such instances.
Public static Singleton GetInstance () This method is used to obtain the unique global access point of the instance.
Lock: ensures that when one thread is located in the Code critical section, the other thread does not enter the critical section. If other threads attempt to enter the locked code, it waits until the object is released.
Then add a test method in the Singleton class above.
Finally, you can call and test the function at the entrance of the console application.
Main(
The result is OK.
Singleton s1 == (s1 ==
Add the instance code to the Main function to determine whether two instantiated objects are one.
In fact, in actual application, the C # and common language runtime libraries also provide a "static initialization" method, which does not require developers to compile thread-safe code, it solves the problem of being insecure in a multi-threaded environment.
Singletons instance = Singletons();
Classes are modified using the sealed modifier to prevent derivation, and the derivation may increase the number of instances.
Create an instance when any member of the class is referenced for the first time. The Common Language Runtime Library processes variable initialization. The instance variable is marked with readonly, which means that variables can only be allocated during static initialization or in the class constructor. Because this static initialization method instantiates itself when it is loaded, it is called a hungry Singleton class in the image, the Processing Method of the singleton mode above is to instantiate itself when it is referenced for the first time, so it becomes a lazy Singleton class.
It is a type of static initialization that instantiates objects upon loading. Therefore, system resources must be occupied in advance. Then, we will be faced with the security problem of multi-threaded access. We need to implement dual locks to ensure security. Which method is used depends on the actual needs. From the perspective of C # language, the hungry Chinese Singleton class is enough to meet our needs.