简单单例
public class Singleton
{
private Singleton(){}
public static readonly Singleton instance = new Singleton();
}
标准单例
public class Singleton
{
private static Singleton _instance = new Singleton();
private Singleton(){}
public static Singleton Instance
{
get
{
return _instance;
}
}
}
泛型单例-正确示例
//泛型单例基类
public class Singleton<T> where T : class
{
static T _instance;
static Singleton()
{
if (_instance == null)
{
Type t = typeof(T);
_instance = (T)Activator.CreateInstance(t, true);
}
}
public static T Instance
{
get
{
return _instance;
}
}
}
//使用方法
public class ClassName: Singleton<ClassName>
{
private ClassName()
{
}
}
泛型单例-错误示例
public class Singleton<T> where T : class
{
static T _instance;
static Singleton()
{
_instance = T();
}
public static T Instance
{
get
{
return _instance;
}
}
}
这样看好像是没有问题的,但是从这个基类继承的话,必须有public 的构造函数
public class ClassName: Singleton<ClassName>
{
public ClassName()
{
}
}
如果老老实实用 Instance.ClassName.xxx
的话没问题,但因为是public的构造函数,所以别人就有权利自己new 一个新的了,严重违背了单例的要求。