单例模式:

步骤:

1.定义静态私有对象

2.构造函数私有化

3.定义一个静态的,返回值为该类型的方法,一般以Getinstance/getInit为方法名称

单例模式有懒汉和饿汉,最好使用饿汉

1.饿汉式---先实例化

public class Singleton
    {
        private static Singleton  _singleton = new Singleton();//1
        private Singleton()  //2
        {
        }
        public static Singleton GetInstance()  //3
        {

            return _singleton;
        }


    }

 

2.懒汉式---后实例化

using System;

namespace 单例懒汉
{

 public class Singleton

    {
        private static Singleton _singleton;   //1
        private Singleton()   // 2
        {

        }
        public static Singleton GetInstance()  3
        {
            if (_singleton == null)
            {
                _singleton = new Singleton();
            }
            return _singleton;
        }
   }
}

 

相关文章:

  • 2021-06-29
  • 2021-05-02
  • 2021-07-16
  • 2022-01-08
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-25
猜你喜欢
  • 2021-07-24
  • 2022-12-23
  • 2021-09-17
  • 2022-12-23
  • 2021-10-24
  • 2022-02-21
  • 2021-11-09
相关资源
相似解决方案