public void CheckCounter() { LazySingleton firstInstance = LazySingleton.getInstance(); firstInstance = LazySingleton.getInstance(); Assert.AreEqual(1, firstInstance.getCounter()); }
//返回对象 public static LazySingleton getInstance() { // 判断如果对象不为null,就不用进入同步块,这样可以提高性能 if (singleton == null) { //判断对象为null,才创建对象 singleton = new LazySingleton(); } return(singleton); }
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(); }