第一种、双锁定法 

public sealed class Singleton
{
static Singleton instance = null;
static readonly object lockhelper = new object();

Singleton()
{
}

public static Singleton Instance
{
get
{
if (instance == null)
{
lock (lockhelper)
{
if (instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}

 

第二种、静态初始化

public sealed class Singleton
{
static readonly Singleton instance = new Singleton();

static Singleton()
{
}

Singleton()
{
}

public static Singleton Instance
{
get
{
return instance;
}
}
}

 

第三种、延时初始化

public sealed class Singleton
{
Singleton()
{
}

public static Singleton Instance
{
get
{
return Nested.instance;
}
}

class Nested
{
static Nested()
{
}

internal static readonly Singleton instance = new Singleton();
}
}

 

相关文章:

  • 2021-10-03
  • 2022-02-04
  • 2022-01-21
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-31
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-01-25
  • 2022-02-09
  • 2022-12-23
  • 2021-08-11
  • 2021-12-16
相关资源
相似解决方案