/// <summary> /// 公有静态构造方法作为构造函数。该函数会“偷偷”调用私有构造函数来创建对象, /// 并将其保存在一个私有静态成员变量中。此后所有对于该函数的调用都将返回这一缓存对象。 /// </summary> /// <returns></returns> public static BaseSingleton GetInstance() { if (_instance == null) { // 注意:如果程序需要支持多线程,必须在此位置放置线程锁 _instance = new BaseSingleton(); } return(_instance); }
static void Main(string[] args) { #region 基础单例 BaseSingleton s1 = BaseSingleton.GetInstance(); BaseSingleton s2 = BaseSingleton.GetInstance(); if (s1 == s2) { Console.WriteLine("Singleton works, both variables contain the same instance."); } else { Console.WriteLine("Singleton failed, variables contain different instances."); } #endregion #region 线程安全单锁单例 Console.WriteLine( "{0}\n{1}\n\n{2}\n", "If you see the same value, then singleton was reused (yay!)", "If you see different values, then 2 singletons were created (booo!!)", "RESULT:" ); Thread process1 = new Thread(() => { TestSingleton("FOO"); }); Thread process2 = new Thread(() => { TestSingleton("BAR"); }); process1.Start(); process2.Start(); process1.Join(); process2.Join(); #endregion #region 线程安全双锁单例 Console.WriteLine(DoubleLockSingleton.Instance.DoSomething("Hay")); Console.WriteLine(DoubleLockSingleton.Instance.DoSomething("Halo")); Console.ReadLine(); #endregion }