设计模式(一):单例
1 /// <summary>
2 /// 饿汉单例模式:类被加载时,将自己类实例化(静态初始化)
3 /// </summary>
4 public sealed class Singleton1
5 {
6 private static readonly Singleton1 instance = new Singleton1();
7 private Singleton1()
8 { }
9
10 public static Singleton1 GetInstance()
11 {
12 return instance;
13 }
14 }
15
16 /// <summary>
17 /// 懒汉单例模式:类第一次被引用时,将自身类实例化
18 /// </summary>
19 public class Singleton2
20 {
21 private static Singleton2 instance;
22 private static readonly object syncRoot = new object();
23
24 private Singleton2()
25 { }
26
27 public static Singleton2 GetInstance()
28 {
29 if (instance == null)
30 {
31 lock (syncRoot)//加锁
32 {
33 if (instance == null)
34 {
35 instance = new Singleton2();
36 }
37 }
38 }
39
40 return instance;
41 }
42 }
2 /// 饿汉单例模式:类被加载时,将自己类实例化(静态初始化)
3 /// </summary>
4 public sealed class Singleton1
5 {
6 private static readonly Singleton1 instance = new Singleton1();
7 private Singleton1()
8 { }
9
10 public static Singleton1 GetInstance()
11 {
12 return instance;
13 }
14 }
15
16 /// <summary>
17 /// 懒汉单例模式:类第一次被引用时,将自身类实例化
18 /// </summary>
19 public class Singleton2
20 {
21 private static Singleton2 instance;
22 private static readonly object syncRoot = new object();
23
24 private Singleton2()
25 { }
26
27 public static Singleton2 GetInstance()
28 {
29 if (instance == null)
30 {
31 lock (syncRoot)//加锁
32 {
33 if (instance == null)
34 {
35 instance = new Singleton2();
36 }
37 }
38 }
39
40 return instance;
41 }
42 }