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


单例模式:

步骤:

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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM