单例模式

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace 单例模式
 7 {
 8     class Studnet
 9     {
10         public string id { get; set; }
11         public string name { get; set; }
12 
13         private static Studnet _instance = null;
14 
15         private Studnet()
16         {
17 
18         }
19 
20 
21         //单例第一种写法
22 
23         private static object _SingleLock = new object();
24         public static Studnet Instance()
25         {
26             //双if加lock
27             if (_instance == null)
28             {
29                 lock (_SingleLock)
30                 {
31                     if (_instance == null)
32                     {
33                         _instance = new Studnet();
34                     }
35                 }
36             }
37             return _instance;
38         }
39 
40 
41         //单例第二种写法
42 
43         /// <summary>
44         /// 创建一个静态构造函数
45         /// </summary>
46         /// 静态构造函数在调用该类之前被CLR自动初始化,常驻内存,不会被GC回收
47         static Studnet()
48         {
49             _instance = new Studnet();
50         }
51         public static Studnet stuInstance()
52         {
53             return _instance;
54         }
55 
56 
57 
58         //单例第三种写法
59 
60         //创建一个私有的静态变量,当调用该类之前创建并且只会被初始化一次
61         private static Studnet stu = new Studnet();
62 
63         public static Studnet InstanceSingle()
64         {
65             return stu;
66         }
67 
68     }
69 }
世界上最可怕事情是比我们优秀的人比我们还努力
原文地址:https://www.cnblogs.com/AlexOneBlogs/p/7309557.html