单例模式的三种写法

时间:2021-09-01 21:16:31

第一种,懒汉模式,没考虑线程安全

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