Singleton模式及单例/单件模式。
类型:创建型模式
Gof定义:保证一个类仅有一个实例,并提供一个该实例全局的访问点。
我们来看集中Singleton模式的例子:
单线程Sinleton
1
///
<summary>
2 /// Single thread Singleton pattern
3 /// </summary>
4 public class Singleton
5 {
6 private static Singleton instance;
7
8 public static Singleton Instance
9 {
10 get
11 {
12 if (instance == null )
13 {
14 instance = new Singleton();
15 }
16 return instance;
17 }
18 }
19
20 private Singleton() { }
21 }
2 /// Single thread Singleton pattern
3 /// </summary>
4 public class Singleton
5 {
6 private static Singleton instance;
7
8 public static Singleton Instance
9 {
10 get
11 {
12 if (instance == null )
13 {
14 instance = new Singleton();
15 }
16 return instance;
17 }
18 }
19
20 private Singleton() { }
21 }
上面的例子在多线程中就会破坏Singleton的原则,及一个类仅有一个实例。
假设有两个线程Thread1和Thread2,Thread1判断instance为null,进入if语句,此时,在new出Singleton实例前,
Thread2也走到了if语句,同样判断instance为null,这样,两个线程分别创建一个Singleton实例,从而破坏了Sinleton的原则。
多线程Singleton
1
///
<summary>
2 /// Multi thread Singleton pattern
3 /// </summary>
4 public class Singleton
5 {
6 private static volatile Singleton instance = null ;
7 private static object lockHelper = new object ();
8
9 public static Singleton Instance
10 {
11 get
12 {
13 if (instance == null )
14 {
15 lock (lockHelper)
16 {
17 if (instance == null )
18 {
19 instance = new Singleton();
20 }
21 }
22 }
23 return instance;
24 }
25 }
26
27 private Singleton() { }
28 }
2 /// Multi thread Singleton pattern
3 /// </summary>
4 public class Singleton
5 {
6 private static volatile Singleton instance = null ;
7 private static object lockHelper = new object ();
8
9 public static Singleton Instance
10 {
11 get
12 {
13 if (instance == null )
14 {
15 lock (lockHelper)
16 {
17 if (instance == null )
18 {
19 instance = new Singleton();
20 }
21 }
22 }
23 return instance;
24 }
25 }
26
27 private Singleton() { }
28 }
精简方式
1
///
<summary>
2 /// Multi thread Singleton pattern
3 /// </summary>
4 class Singleton
5 {
6 public static readonly Singleton Instance = new Singleton();
7 private Singleton() { }
8 }
2 /// Multi thread Singleton pattern
3 /// </summary>
4 class Singleton
5 {
6 public static readonly Singleton Instance = new Singleton();
7 private Singleton() { }
8 }
等同于以下方式
精简方式还原
1
///
<summary>
2 /// Multi thread Singleton pattern
3 /// </summary>
4 class Singleton
5 {
6 public static readonly Singleton Instance;
7
8 static Singleton ()
9 {
10 Instance = new Singleton();
11 }
12 private Singleton() { }
13 }
2 /// Multi thread Singleton pattern
3 /// </summary>
4 class Singleton
5 {
6 public static readonly Singleton Instance;
7
8 static Singleton ()
9 {
10 Instance = new Singleton();
11 }
12 private Singleton() { }
13 }
如何验证Singleton模式
验证Singleton
1
private
bool
VerifySingletonPattern()
2 {
3 Singleton s1 = Singleton.Instance;
4 Singleton s2 = Singleton.Instance;
5
6 return object .ReferenceEquals(s1, s2);
7 }
2 {
3 Singleton s1 = Singleton.Instance;
4 Singleton s2 = Singleton.Instance;
5
6 return object .ReferenceEquals(s1, s2);
7 }
注:本系列博客来自WebCasts 李建忠的讲座。