單例模式(Singleton):保證一個類僅有一個實例,並提供一個訪問它的全局訪問點。
單例模式(單件模式)
使用方法返回唯一的實例
public class SingLeton
{
//創建一個私有的構造函數(必須),堵住外界使用new創建此實例的可能
private SingLeton()
{
}
private static SingLeton instance;
public static SingLeton GetInstance()
{
if (instance ==null )
{
instance = new SingLeton();
}
return instance;
}
}
使用屬性返回唯一的實例
public class SingLeton
{
//創建一個私有的構造函數(必須),堵住外界使用new創建此實例的可能
private SingLeton()
{
}
private static SingLeton instance;
public static SingLeton Instance
{
get
{
if (instance==null )
{
instance = new SingLeton();
}
return instance;
}
}
}
多線程訪問時需要對實例進行加鎖
public class SingLeton
{
//創建一個私有的構造函數(必須),堵住外界使用new創建此實例的可能
private SingLeton()
{
}
private static SingLeton instance;
//定義一個輻助對象
private static object obj = new object();
//多線程使用單例模式(double check 雙重檢查)
public static SingLeton GetInstances()
{
if (instance ==null )
{
lock (obj) //爲實例加鎖
{
if (instance ==null)
{
instance = new SingLeton();
}
}
}
return instance;
}
}
在C#與公共語言運行庫也提供了一種“靜態初始化”方法,這種方法不需要開發人員顯式地編寫線程安全代碼,即可解決多線程環境下它是不安全的問題
public sealed class Singleton
{
//1.使用readonly的方式
private static readonly Singleton instance = new Singleton();
private Singleton()
{
}
public static Singleton GetInstance()
{
return instance;
}
}
由於這種靜態初始化方式是自己被加載時就將自己實例化,所以被形象地稱之爲餓漢式單例類,上面兩種處理方式是要在第一次被引用時,纔會將自己實例化,所以就被稱爲懶漢式單例類。
由於餓漢式,即靜態初始化方式,是類一加載就實例化,所以要提前佔用系統資源,然而懶漢式,又會面臨多線程訪問安全性的問題,需要雙重鎖定的處理纔可以保證安全。所在到底使用哪一種方式,取決於實際的需求。