单例

 1 /// <summary>
 2     /// 单线程单例
 3     /// </summary>
 4     public class SingleThreadSingleton
 5     {
 6         //保存实例容器
 7         private static SingleThreadSingleton instance = null;
 8         private SingleThreadSingleton() { }
 9         //通过属性暴露静态实例
10         public static SingleThreadSingleton Instance
11         {
12             get 
13             {
14                 //多线程下此处会出现竞争导致的错误,保持不了一直是一个实例
15                 if (instance == null)
16                 {
17                     instance = new SingleThreadSingleton();
18                 }
19                 return instance;
20             }
21         }
22     }
23 
24     /// <summary>
25     /// 多线程下单例
26     /// </summary>
27     public class MultiThreadSingleton
28     {
29         //volatile 保证严格意义的多线程编译器在代码编译时对指令不进行微调。
30         private static volatile MultiThreadSingleton instance = null;
31         //防止竞争资源导致的实例不唯一
32         private static object lockHelper = new object();
33         private MultiThreadSingleton() { }
34         public static MultiThreadSingleton Instance
35         {
36             get 
37             {
38                 if (instance == null)
39                 {
40                     lock (lockHelper)
41                     {
42                         if (instance == null)
43                         {
44                             instance = new MultiThreadSingleton();
45                         }
46 
47                     }
48                 }
49                 return instance;
50             }
51         }
52     }
53 
54     //静态单例
55     public class StaticSingleton
56     {
57         public static readonly StaticSingleton instance = new StaticSingleton();
58         private StaticSingleton() { }
59     }

ps:

单例即

  保持同一个实例,所以选私有静态。

  属性暴露实例

  私有构造函数 保证外部不能实例化

  -------------------

  多线程加锁

  保证实例唯一

  ------------------ 

 

posted @ 2021-03-10 09:57  mollom  阅读(56)  评论(0编辑  收藏  举报