单例模式
单例模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
结构图:
//单线程
class Singleton
{
private static Singleton instance;
private Singleton()
{ }
public static Singleton GetInstance()
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
{
private static Singleton instance;
private Singleton()
{ }
public static Singleton GetInstance()
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
//多线程
class Singleton2
{
private static Singleton2 instance;
private static readonly object synvRoot = new object();
private Singleton2()
{ }
public static Singleton2 GetInstance()
{
if (instance == null)
{
lock (synvRoot)
{
if (instance == null)
{
instance = new Singleton2();
}
}
}
return instance;
}
//线程【串行化】的方式睡眠了 20 毫秒
public static void ddd()
{
lock (synvRoot)
System.Threading.Thread.Sleep(20);
}
}
{
private static Singleton2 instance;
private static readonly object synvRoot = new object();
private Singleton2()
{ }
public static Singleton2 GetInstance()
{
if (instance == null)
{
lock (synvRoot)
{
if (instance == null)
{
instance = new Singleton2();
}
}
}
return instance;
}
//线程【串行化】的方式睡眠了 20 毫秒
public static void ddd()
{
lock (synvRoot)
System.Threading.Thread.Sleep(20);
}
}
主函数:
class Program
{
static void Main(string[] args)
{
Singleton s1 = Singleton.GetInstance();
Singleton s2 = Singleton.GetInstance();
if (s1 == s2)
{
Console.WriteLine("s1和s2是相同实例");
}
//多线程
Singleton2 s3 = Singleton2.GetInstance();
Singleton2 s4 = Singleton2.GetInstance();
if (s3 == s4)
{
Console.WriteLine("s1和s2是相同实例");
}
Console.ReadKey();
}
}
{
static void Main(string[] args)
{
Singleton s1 = Singleton.GetInstance();
Singleton s2 = Singleton.GetInstance();
if (s1 == s2)
{
Console.WriteLine("s1和s2是相同实例");
}
//多线程
Singleton2 s3 = Singleton2.GetInstance();
Singleton2 s4 = Singleton2.GetInstance();
if (s3 == s4)
{
Console.WriteLine("s1和s2是相同实例");
}
Console.ReadKey();
}
}
Lock是确保当一个线程位于代码的临界区时,另一个线程不进入临界区,如果其他线程试图进入锁定的代码,侧他将一直等待,直到被该对象释放。