定义:
单例模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
示例:
public class Singleton
{
private static volatile Singleton singleton;
private static object test = new object();
private Singleton() { }
public static Singleton GetSingletonInstance()
{
//使用双重检查加锁机制,保证线程安全
if (singleton == null)
{
lock (test)
{
if (singleton == null)
{
singleton = new Singleton();
}
}
}
return singleton;
}
}
{
private static volatile Singleton singleton;
private static object test = new object();
private Singleton() { }
public static Singleton GetSingletonInstance()
{
//使用双重检查加锁机制,保证线程安全
if (singleton == null)
{
lock (test)
{
if (singleton == null)
{
singleton = new Singleton();
}
}
}
return singleton;
}
}