Singleton pattern ensures that a class can only be instantiated once and provides a global access point to access it.
There are two methods to use the standalone mode.
1. Use a static variable.
2. Use the constructor to judge.
First, use the static variable method,
We use an entity instance to determine whether the current class has been instantiated. If not, a singleton instance is added. However, this method is not recommended for everyone. If it is a multi-threaded tool for operation, your concept of monomer will disappear. Therefore, we need to add an object and use a lock to lock the object to prevent multi-thread instantiation. That is, the comments section in.
Private Static readonly object padload = new object ();
Lock (padload)
The second method is to set the constructor as a common method. However, a counter with a static variable is used to restrict the class from being instantiated twice.
If the counter is not zero, an exception is thrown to it.
Check the running result:
When singleton2 is instantiated multiple times:
Throw an exception.