Single-piece mode ensures that only one instance of the same type
Steps:
Declare the class as sealed to prevent it from being inherited and declare the constructor as private to prevent it from being instantiated.
It ensures that it can only be accessed as a static class and the uniqueness of the global instance.
PassPublic StaticT getinstance ()
Obtains the reference of a unique generic instance. If the reference is null, a new instance new T () is created ()
Code
/// <Summary>
/// Singleton generic class
/// </Summary>
/// <Typeparam name = "T"> </typeparam>
Public Sealed Class Singleton < T > Where T: New ()
{
Private Static T instance = New T ();
Private Static Object Lockhelper = New Object ();
/// <Summary>
/// Constructor
/// </Summary>
Private Singleton ()
{}
/// <Summary>
/// Get instance
/// </Summary>
/// <Param name = "value"> </param>
Public Static T getinstance ()
{
If (Instance = Null ) // Note that instance = NULL is determined here to prevent lock from being used for each access to this method.
{
Lock (Lockhelper)
{
If (Instance = Null ) // The second time
{
Instance = New T ();
}
}
}
ReturnInstance;
}
/// <Summary>
/// Set instance
/// </Summary>
/// <Param name = "value"> </param>
Public static Void Setinstance (T value)
{
Instance = Value;
}
}
LockKeyword to ensure that when a thread is locatedCodeThe other thread does not enter the critical section. If other threads attempt to enter the locked code, it waits until the object is released.
LockThe keyword is called at the beginning of the block. And at the end of the block .
Generally, do not lockPublicType. Otherwise, the instance is out of the control range of the Code. Common StructureLock (this),Lock (typeof (mytype ))AndLock ("mylock ")Violation of this rule:
If the instance can be accessed by the publicLock (this)Problem.
IfMytypePublic access is allowed.Lock (typeof (mytype ))Problem.
Any other code that uses the same string in the process will share the same lock.Lock ("mylock ")Problem.
The best practice is to definePrivateObject To lock, orPrivate StaticObject variables to protect the data shared by all instances.