.Net today learned of the singleton pattern mainly into three.
1, a single mode single-threaded environment to achieve
PS. In the absence of private, the compiler will automatically generate construction of a public. It is necessary to declare a private constructor private.
namespace Singleton
{
public class Singleton
{
private Singleton() { }
private static Singleton instance;
public static Singleton Instance
{
get
{
if(instance == null)
instance = new Singleton();
return instance;
}
}
}
}
2, to achieve the double locking of multiple threads
namespace SigletonPattern.Sigleton
{ / ** / /// <the Summary> /// function: C # using double-lock mode to achieve a single piece /// write: TerryLee /// Date: December 6, 2005 / // </ Summary> public class DoubLockSigleton { // volatile that the compiler can not optimize automatic debugging statements (statement to avoid adjusting the position and sequence resulting in incorrect initialization time point .sky). Private static volatile DoubLockSigleton instance; / ** / // / <Summary> /// secondary lock object itself meaningless /// </ Summary> Private static Object SyncRoot = new new
Object();
/**//// <summary>
/// 构造方法改为Private
/// </summary>
private DoubLockSigleton()
{
}
public static DoubLockSigleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new DoubLockSigleton();
}
}
return instance;
}
}
}
}
3, the legend of the method in the MSDN article provided treatment singleton pattern realization of the principle of using the C # static properties and static constructor.
namespace Singleton
{
public class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton() { }
}
}
编译后查看il可以发现其实是等同于下面的代码的
namespace Singleton
{
public class Singleton
{
private static readonly Singleton instance;
static Singleton()
{
instance = new Singleton();
}
private Singleton() { }
}
}
Because C # static properties and static constructor mechanism, call the static attribute instance, when will first perform a static constructor of the class, but also to ensure that only one thread can execute static constructors. So to achieve a singleton pattern.
Reproduced in: https: //www.cnblogs.com/wysky/archive/2008/07/23/csharp_singleton.html