当前位置: 移动技术网 > IT编程>开发语言>.net > C#单例---饿汉式和懒汉式

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

2018年11月01日  | 移动技术网IT编程  | 我要评论

杭州公积金,世界洋流分布图,沈崇事件

单例模式:

步骤:

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

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网