简单的单例:
1 public class Student 2 { 3 //1。私有静态变量 4 private static Student stu = null; 5 6 //2。私有化构造函数 7 private Student() 8 { 9 } 10 11 //3.提供一个静态方法让外部可以访问得到 12 public static Student GetInstance() 13 { 14 if (stu == null) 15 { 16 stu = new Student(); 17 } 18 return stu; 19 } 20 }
多线程单例:
1 //1。私有静态变量 2 private static Student stu = null; 3 private static object _lock = new object(); 4 5 //2。私有化构造函数 6 private Student() 7 { 8 } 9 10 //3.提供一个静态方法让外部可以访问得到 11 public static Student GetInstance() 12 { 13 if (stu == null) 14 { 15 lock (_lock) 16 { 17 if (stu==null) 18 { 19 stu = new Student(); 20 } 21 } 22 23 } 24 return stu; 25 }