说明:
- 单例模式——在整个进程中,只被实例化一次
- 单例模式的好处——只允许创建一个对象,因此节省内存,加快访问对象的速度
- 单例模式的坏处——如果同一个单例在不同的用例场景中发生变化,就会出现数据错误,也就是不适用与变化的对象。
常见的单例写法:
单线程环境下:
/// <summary>
/// 适用于单线程情况下,在Unity这类引擎中满足使用
/// </summary>
public class Singleton
{
static Singleton instance = null;
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
在多线程环境下:
/// <summary>
/// 适用于多线程情况下,确保线程安全
/// </summary>
public class Singleton
{
static Singleton instance = null;
static Object lockObj = new Object();
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (lockObj)
{
if (instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}
/// <summary>
/// 静态构造方法:CLR运行时,第一次使用这个类之前,会而且只会执行一次
/// </summary>
public class Singleton
{
static Singleton instance = null;
static Singleton()
{
instance = new Singleton();
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
public class single<T>where T:new ()
{
private static T singleClass;
public static T Instance
{
get
{
if (singleClass == null)
{
singleClass =new T();
}
return singleClass;
}
}
}