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