一:幼年体(只适用于单线程)
1.设置单例
public class Singleton
{
private static Singleton _Singleton = null;
public static Singleton CreateInstance()
{
if (_Singleton == null)
{
_Singleton = new Singleton();
Console.WriteLine("单例已被创建");
}
return _Singleton;
}
}
2.使用单例
static void Main(string[] args)
{
TaskFactory taskFactory = new TaskFactory();
List<Task> taskList = new List<Task>();
for (int i = 0; i < 5; i++)
{ //当多个线程同时判断单例对象为空,那么这个对象将会被创建了几次,因此单例失去了意义
taskList.Add(taskFactory.StartNew(()=> { Singleton s = Singleton.CreateIntance(); }));
}
Console.ReadKey();
}
二:完全体(可适用于多线程)
设置单例时加一把锁,禁止多个线程同时访问该对象资源
public class Singleton
{
private static Singleton s = null;
private static object singletonLock = new object(); //锁同步
public static Singleton CreateIntance()
{
lock (singletonLock)
{
if (s == null)
{
s = new Singleton();
Console.WriteLine("此类被创建");
}
}
return s;
}
}
三:究极体(当单例已被创建时,后者的线程无需再判断单例是否被创建)
public class Singleton
{
private static Singleton s = null;
private static object singletonLock = new object(); //锁同步
public static Singleton CreateIntance()
{
if (s == null)
{
lock (singletonLock)
{
if (s == null)
{
s = new Singleton();
Console.WriteLine("此类被创建");
}
}
}
return s;
}
}