單例模式:
步驟:
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; } }
}