1 ///<summary> 2 /// 尝试单例模式 3 /// </summary> 4 public class Db 5 { 6 /// <summary> 7 /// 需要的数据库 8 /// </summary> 9 private static readonly SPMEntities db = new SPMEntities();//因为该字段是静态的,而所在类又是单例的,所以该类生命周期中,该字段不会变。 10 static volatile Db _instance = null; 11 static readonly object padlock = new object(); 12 /// <summary> 13 /// 私有的构造方法 14 /// </summary> 15 private Db() 16 { 17 18 } 19 public static Db GetInstance() //防止多线程并发导致失去单例,因此多重检测 20 { 21 if (_instance == null) 22 { 23 lock (padlock) 24 { 25 if (_instance == null) 26 { 27 _instance = new Db(); 28 } 29 } 30 } 31 return _instance; 32 } 33 public SPMEntities GetDb()//声明为实例方法,调用时可以这样: var entities = Db.GetInstance().GetDb(); 34 { 35 return db; 36 } 37 }