public void AreSingletonHashcodesSame() { LazySingleton firstInstance = LazySingleton.getInstance(); LazySingleton secondInstance = LazySingleton.getInstance(); Assert.AreEqual(firstInstance.GetHashCode(), secondInstance.GetHashCode()); }
public void AreSingletonInstancesSame() { LazySingleton firstInstance = LazySingleton.getInstance(); LazySingleton secondInstance = LazySingleton.getInstance(); Assert.AreSame(firstInstance, secondInstance); }
public void CheckCounter() { LazySingleton firstInstance = LazySingleton.getInstance(); firstInstance = LazySingleton.getInstance(); Assert.AreEqual(1, firstInstance.getCounter()); }
static void Main(string[] args) { Console.WriteLine("饿汉式单例模式"); Console.WriteLine(); //通过new实例化会报错 Singleton g = new Singleton(); //只能通过getInstance得到对象 Singleton g1 = Singleton.getInstance(); Console.ReadKey(); Console.WriteLine("懒汉式单例模式"); Console.WriteLine(); Console.WriteLine("单线程环境"); for (int i = 0; i < 10; i++) { LazySingleton singleton = LazySingleton.getInstance(); } Console.ReadKey(); }