欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#单例---饿汉式和懒汉式

程序员文章站 2022-06-28 12:54:18
单例模式: 步骤: 1.定义静态私有对象 2.构造函数私有化 3.定义一个静态的,返回值为该类型的方法,一般以Getinstance/getInit为方法名称 单例模式有懒汉和饿汉,最好使用饿汉 1.饿汉式 先实例化 2.懒汉式 后实例化 using System; namespace 单例懒汉{ ......

单例模式:

步骤:

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;
        }
   }
}