上面分别说了单件模式在单线程和多线程的实现,下面介绍一种简单的方法,可以同时满足这两种,使用静态构造函数来实现。静态构造函数只在静态字段初始化之前初始化,就是说我们在访问访问静态字段会先访问静态构造函数。静态构造函数可以保证多线程中只有一个线程执行该静态构造函数,关于Net中静态构造函数机制可以参考CLR Via C# 学习笔记(5) 静态构造函数的性能
1 2 3 4 5
public class Singleton { public static readonly Singleton _Instance = new Singleton(); private Singleton() { } }
上面的代码等同于
1 2 3 4 5 6 7 8 9
public class Singleton { public static readonly Singleton _Instance; static Singleton() { _Instance = new Singleton(); } private Singleton() { } }
public class Singleton { public static readonly Singleton _Instance; static Singleton() { _Instance = new Singleton(); } private Singleton() { } //添加属性,在调用的时候直接给属性赋值 public Int32 X { get { return _x; } set { _x = value; } }
public Int32 Y { get { return _y; } set { _y = value; } } private Int32 _x; private Int32 _y; }
调用代码:
1 2 3 4 5 6 7 8 9
public class Test { public static void Main() { Singleton t = Singleton._Instance ; t.X = 100; t.Y = 200; } }