1、/// <summary>
/// 多线程下的懒汉式单例模式,不加锁会出现多线程同时创建对象的问题,违反了单例模式原则。
/// </summary>
public class Singleton
{
private static Singleton instance;
private static object _lock = new object();
private Singleton()
{
}
public static Singleton GetInstance()
{
if (instance == null)
{
lock (_lock)
{
if (instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
2、饿汉模式。由于一开始就创建了对象,所以不会存在多线程调用同时创建对象的问题
public class Singleton
{
private static Singleton instance=new Singleton();
private Singleton() { }
public static Singleton GetInstance()
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}