定义确保一个类仅有一个实例,并提供一个访问它的全局访问点

优点:在内存中只有一个对象,节省了内存空间

示例

Singleton.cs    

写法一:非线程安全

 public class Singleton
    {
        //声明一个静态的类变量
        private static Singleton singleton;

        /// <summary>
        /// 私有构造函数,避免外部代码new实例化对象
        /// </summary>
        private Singleton()
        {

        }

        /// <summary>
        /// 实例化对象
        /// </summary>
        /// <returns></returns>
        public static Singleton GetInstance()
        {
            if (singleton == null)
            {
                singleton = new Singleton();
            }

            return singleton;
        }
    }
View Code

相关文章:

  • 2021-11-09
  • 2021-10-29
  • 2021-10-07
  • 2022-01-20
  • 2021-09-01
猜你喜欢
  • 2021-06-06
  • 2021-11-19
  • 2021-08-23
  • 2021-04-12
  • 2021-10-12
  • 2021-09-16
  • 2021-05-18
相关资源
相似解决方案