1. Locking Singleton Mode
Public class CommonService
{
Private static CommonService instance;
Private static readonly object syncRoot = new object ();
Private CommonService ()
{
}
Public static CommonService GetInstance ()
{
If (instance = null)
{
Lock (syncRoot)
{
If (instance = null)
{
Instance = new CommonService ();
}
}
}
Return instance;
}
}
2. When the first call is delayed, the initial CommonService will not be regenerated in the future.
Static Initialization
The thread-safe code compilation is not required to be displayed. This solves the problem that the single-threaded environment ordering Mode is insecure.
Public sealed class CommonService
{
Private static readonly CommonService instance = new CommonService ();
Private CommonService (){}
Public static CommonService GetInstance ()
{
Return instance;
}
}
Appendix:
1. What is the purpose of a Singleton?
This should be obvious, to ensure that a class only has a single instance, that is, you cannot create a New instance of this class through New or CreateInstance.
2. What are the benefits of Singleton?
When an object can only have one instance in the program, it can ensure that we do not create it again, but always point to the same object.
3. How to use it?
The implementation code of Singleton mode is as follows:
Namespace SinglePattern
{
Public class SingleClass
{
Private static SingleClass instance;
Protected SingleClass (){}
Public static SingleClass GetInstance ()
{
If (instance = null)
{
Instance = new SingleClass ();
}
Return instance;
}
}
}
The above code can be said to be a standard Singleton code, but the above Code may generate multiple instances when multithreading, in order to avoid this situation, we need to restrict access by only one thread at a time.
Using lock can achieve our goal:
Namespace SinglePattern
{
Public class SingleClass
{
// Static variables
Private static SingleClass instance;
// "Lock" variable
Private static object lockObject = new objest ();
// Protected Constructor
Protected SingleClass (){}
// Static object Acquisition Method
Public static SingleClass GetInstance ()
{
Lock (lockObject)
{
If (instance = null)
{
Instance = new SingleClass ();
}
}
Return instance;
}
}
}
Another method:
After adjustment, this method can also be used to limit that only one instance can be started for one form.
Using System. Threading;
Namespace SinglePattern
{
Public class SingleClass
{
// Static variables
Private static SingleClass instance;
// Protected Constructor
Protected SingleClass (){}
// Static object Acquisition Method
Public static SingleClass GetInstance ()
{
Mutex mutex = new Mutex ();
Mutex. WaitOne ();
If (instance = null)
{
Instance = new SingleClass ();
}
Mutex. Close ();
Return instance;
}
}
}