单件模式(Singleton Pattern)
单件模式是一个创建型模式(Creational Pattern)保证一个类仅有一个实例,并提供一个访问它的全局访问点。实现方式有两种:
方法1:
1 public sealed class Singleton
2 {
3 //lazy load
4 private volatile static Singleton uniqueInstance = null;
5
6 //多线程下的锁控制
7 private static object locker = new object();
8
9 private int X;
10 private int Y;
11
12 private Singleton(int x,int y)
13 {
14 X = x;
15 Y = y;
16 }
17
18 public static Singleton GetInstance(int x, int y)
19 {
20 if (uniqueInstance == null)
21 {
22 lock (locker)
23 {
24 if (uniqueInstance == null)
25 {
26 uniqueInstance = new Singleton(x, y);
27 }
28 }
29 }
30 else
31 {
32 uniqueInstance.X = x;
33 uniqueInstance.Y = y;
34 }
35
36 return uniqueInstance;
37 }
38 }
2 {
3 //lazy load
4 private volatile static Singleton uniqueInstance = null;
5
6 //多线程下的锁控制
7 private static object locker = new object();
8
9 private int X;
10 private int Y;
11
12 private Singleton(int x,int y)
13 {
14 X = x;
15 Y = y;
16 }
17
18 public static Singleton GetInstance(int x, int y)
19 {
20 if (uniqueInstance == null)
21 {
22 lock (locker)
23 {
24 if (uniqueInstance == null)
25 {
26 uniqueInstance = new Singleton(x, y);
27 }
28 }
29 }
30 else
31 {
32 uniqueInstance.X = x;
33 uniqueInstance.Y = y;
34 }
35
36 return uniqueInstance;
37 }
38 }
方法2:
1 public sealed class SingletonStatic
2 {
3 //这里其实也是lazy load,new操作被推迟到静态构造函数中执行
4 public static readonly SingletonStatic instance = new SingletonStatic();
5
6 private SingletonStatic() { }
7
8 public int X { get; set; }
9
10 public int Y { get; set; }
11 }
2 {
3 //这里其实也是lazy load,new操作被推迟到静态构造函数中执行
4 public static readonly SingletonStatic instance = new SingletonStatic();
5
6 private SingletonStatic() { }
7
8 public int X { get; set; }
9
10 public int Y { get; set; }
11 }