Ejemplo n.º 1
0
        public static readonly object Locker = new object();//readonly只读 ;const常量

        /// <summary>
        /// 定义公有方法来生成类的实例
        /// </summary>
        /// <returns></returns>
        public static SingletonDemo GetInstance()
        {
            //构造函数私有化,外部无法new实例,所以需要提供静态的方法
            if (Instance == null)
            {
                Instance = new SingletonDemo();
            }
            return(Instance);
        }
Ejemplo n.º 2
0
 /// <summary>
 /// 线程安全的单例
 /// </summary>
 /// <returns></returns>
 public static SingletonDemo GetInstanceThreadSafe()
 {
     if (Instance == null)
     {
         lock (Locker)
         {
             if (Instance == null)
             {
                 Instance = new SingletonDemo();
             }
         }
     }
     return(Instance);
 }