This pattern seems to be often discussed. I think the theoretical significance is greater than the actual significance. So let's list three types of writing methods.
1. Common writing
Using System;
Public Class Singleton
{
Private Static Singleton instance;
Private Singleton (){}
Public Static Singleton instance
{
Get
{
If (Instance = Null )
{
Instance = New Singleton ();
}
Return Instance;
}
}
}
Advantages: 1. It can be extended and inherit from sub-classes. 2. The object will be instantiated as needed. The disadvantage is that it is not thread-safe.
2. Easy Writing
Public Sealed Class Singleton
{
Private Static Readonly Singleton instance = New Singleton ();
Private Singleton (){}
Public Static Singleton instance
{
Get
{
Return Instance;
}
}
}
This is simple and straightforward, and it will only be instantiated during access. To put it bluntly, you can only use the default constructor and cannot add any other operations.
3. Universal implementation
Using System;
Public Sealed ClassSingleton
{
Private Static VolatileSingleton instance;
Private Static ObjectSyncroot =NewObject ();
PrivateSingleton (){}
Public Static Singleton instance
{
Get
{
If (Instance = Null )
{
Lock (Syncroot)
{
If (Instance = Null )
Instance = New Singleton ();
}
}
Return Instance;
}
}
}
Volatile Keywords are very important. When multithreading is used, the actual memory variable will be retrieved again, and the value in the cache will not be accessed.