单例的特性:一、构造方法私有;二、 定义SingleInstance 类型属性
一、不安全的单例
public class SingleInstance
{
private static SingleInstanceinstance = null;
public static SingleInstance instance
{
get
{
if (instance == null)
{
instance = new SingleInstance();
}
return instance;
}
}
}
这个在多线程的时候if会同时成立,new 两个单例。
二、线程安全的
public sealed class SingleInstance
{
public static readonly SingleInstance instance = new SingleInstance();
static SingleInstance() { }
private SingleInstance() { }//构造函数默认==私有
public static SingleInstance Instance
{
get { return instance; }
}
}
这个instance 并不会在程序启动new一个,也是第一次访问Instance变量时会执行初始化操作。也可以如下写:
public sealed class SingleInstance
{
privete static readonly SingleInstance instance ;
static SingleInstance() {
instance=new SingleInstance ();
}
private SingleInstance() { }//构造函数默认==私有
public static SingleInstance Instance
{
get { return instance; }
}
}
区别: 前者调用的时候顺序是私有构造--->静态构造--->单例get;后者调用静态构造--->私有构造--->单例get
注意:
静态构造函数:只能有一个,无参数的,程序无法调用 。同样是由CLR保证,在程序第一次使用该类之前被调用,而且只调用一次,同静态变量一样。