/// <Summary>
/// threaded singleton pattern sample code
/// This single piece mode in a multithreaded program, can achieve the intended purpose]
/// where volatile represents compiler code is no longer optimized sequence
// / </ Summary>
class the Singleton
{
private volatile static instance the Singleton = null;
/// <Summary>
/// a private constructor
/// </ Summary>
private the Singleton () {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
/// <Summary>
/// single piece of multi-thread mode code
/// </ summary>
SingletonTest class
{
Private volatile static instance the Singleton = null;
/// <Summary>
/// a temporary object to ensure that only one object of this access code below, but easily cause deadlock
/// </ Summary>
public Object Object = new new TEMP ();
/// <Summary>
/// a private constructor
/// </ Summary>
private SingletonTest () {}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (temp)
{
if (instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}
/// <summary>
Another implementation mode of the single-piece ///
/// </ Summary>
class SingletonSecond
{
public static Readonly SingletonSecond new new instance SingletonSecond = ();
/// <the Summary>
/// static constructor
/// does not allow any parameters passed, but the above two classes can have parameters at construction time
/// only one static constructor, this static configuration is called automatically by the program
/// </ Summary>
static SingletonSecond () {}
}
/// <Summary>
/// This class is a detailed explanation of the above-described type
/// following codes, and code a logical above class, but a detailed explanation
/// </ Summary>
class SimpleSingleton
{
public static instance Readonly SimpleSingleton = new SimpleSingleton ();
static SimpleSingleton()
{
new SimpleSingleton();
}
private SimpleSingleton() { }
}
Reproduced in: https: //www.cnblogs.com/liuzhiyi7288/archive/2009/02/20/1395206.html