欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C#单例模式的三种写法

程序员文章站 2022-07-13 23:34:22
...

public class Singleton
{
private static Singleton _instance = null;
private Singleton(){}
public static Singleton CreateInstance()
{
if(_instance == null)

{
_instance = new Singleton();
}
return _instance;
}
}


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;
}
}


public class Singleton
{

private Singleton(){}
public static readonly Singleton instance = new Singleton();
}
相关标签: C C++ C#