在项目里,看到了一段单例的实现代码,想到以前看TerryLee的单例模式时,提到的那个延迟初始化的实现方式,原来就是这样用的。
public class Singleton
{
class Nest
{
static Nest() { }
internal static readonly Singleton instance = new Singleton();
}
public static Singleton Instance
{
get { return Nest.instance; }
}
}
{
class Nest
{
static Nest() { }
internal static readonly Singleton instance = new Singleton();
}
public static Singleton Instance
{
get { return Nest.instance; }
}
}
另外,项目里用得更多的是双重检测的单例
public class Singleton2
{
private Singleton2() { }
private static object sync = new object();
private static Singleton2 instance;
public static Singleton2 Instance
{
get
{
if (instance == null)
{
lock (sync)
{
if (instance == null)
{
instance = new Singleton2();
}
}
}
return instance;
}
}
}
{
private Singleton2() { }
private static object sync = new object();
private static Singleton2 instance;
public static Singleton2 Instance
{
get
{
if (instance == null)
{
lock (sync)
{
if (instance == null)
{
instance = new Singleton2();
}
}
}
return instance;
}
}
}