单例模式
记录下单例模式,方便以后使用:
//单例模式 //包含静态构造函数 //公开的静态方法——提供对象实例,没有就创建 //全局唯一静态实例 public class Singleton { private static Singleton singleton; private static readonly object singletonLock = new object(); //用于测试 public string sDBconnection = ""; private Singleton(string sdb) { sDBconnection = sdb; Console.WriteLine("构造函数初始化!!"); } public static Singleton CreateInstance(string sdb) { if (singleton == null) { lock (singletonLock) { if (singleton == null) { singleton = new Singleton(sdb); } } } return singleton; } }
Main,方法中调用:
static void Main(string[] args) { Singleton singleton = Singleton.CreateInstance("server=1;database=a"); Singleton singleton1 = Singleton.CreateInstance("server=2;database=b"); Singleton singleton2 = Singleton.CreateInstance("server=3;database=c"); Singleton singleton3 = Singleton.CreateInstance("server=4;database=d"); Console.WriteLine(singleton.sDBconnection); Console.WriteLine(singleton1.sDBconnection); Console.WriteLine(singleton2.sDBconnection); Console.WriteLine(singleton3.sDBconnection); Console.Read(); }
输出结果: