The first one is the simplest, but thread security is not taken into account. problems may occur in multithreading. However, I have never seen any errors, and my tables despise me ......
Public class Singleton
{
Private static Singleton _ instance = null;
Private Singleton (){}
Public static Singleton CreateInstance ()
{
If (_ instance = null)
{
_ Instance = new Singleton ();
}
Return _ instance;
}
}
The second method considers thread security, but it is a bit annoying, but it is definitely a regular writing method, a classic cross
Public class Singleton
{
Private volatile static Singleton _ instance = null;
Private static readonly object lockHelper = new object ();
Private Singleton (){}
Public static Singleton CreateInstance ()
{
If (_ instance = null)
{
Lock (lockHelper)
{
If (_ instance = null)
_ Instance = new Singleton ();
}
}
Return _ instance;
}
}
The third possible reason is that C # is unique to other advanced languages.
Public class Singleton
{
Private Singleton (){}
Public static readonly Singleton instance = new Singleton ();
}
Oh, shit!