定義:(Singleton Pattern)
確保某一個類只有一個實(shí)例,而且自行實(shí)例化并向整個系統(tǒng)提供這個實(shí)例。
類圖:

應(yīng)用場景:
避免產(chǎn)生多個對象消耗過多的資源(特別是一個對象需要頻繁的創(chuàng)建和銷毀時);
提供一個全局訪問點(diǎn),常常被用來管理系統(tǒng)中共享的資源(作為一個Manager)。
實(shí)現(xiàn)方式:
一、靜態(tài)變量初始化(餓漢模式)
代碼:
/// <summary>
/// 單例模式實(shí)現(xiàn)方式一:
/// 靜態(tài)變量初始化
/// </summary>
public class Singleton1
{
/// <summary>
/// 定義為靜態(tài)變量,由所有對象共享
/// </summary>
private static Singleton1 instance = new Singleton1();
/// <summary>
/// 構(gòu)造函數(shù)私有化,禁止外部類實(shí)例化該類對象
/// </summary>
private Singleton1()
{
}
public static Singleton1 Instance()
{
return instance;
}
}
應(yīng)用場景:
適用于單線程應(yīng)用程序
二、延遲初始化(懶漢模式)
代碼:
/// <summary>
/// 單例模式實(shí)現(xiàn)方式二:
/// 延遲初始化
/// </summary>
public class Singleton2
{
/// <summary>
/// 定義為靜態(tài)變量,由所有對象共享
/// </summary>
private static Singleton2 _instance;
/// <summary>
/// 構(gòu)造函數(shù)私有化,禁止外部類實(shí)例化該類對象
/// </summary>
private Singleton2()
{
}
public static Singleton2 Instance()
{
return _instance ?? (_instance = new Singleton2());
}
}
三、鎖機(jī)制(推薦)
代碼:
/// <summary>
/// 單例模式實(shí)現(xiàn)方式三:
/// 鎖機(jī)制,確保多線程只產(chǎn)生一個實(shí)例
/// </summary>
public class Singleton3
{
private static Singleton3 _instance;
private static readonly object Locker =new object();
private Singleton3() { }
public static Singleton3 Instance()
{
//沒有第一重 instance == null 的話,每一次有線程進(jìn)入 GetInstance()時,均會執(zhí)行鎖定操作來實(shí)現(xiàn)線程同步,
//非常耗費(fèi)性能 增加第一重instance ==null 成立時的情況下執(zhí)行一次鎖定以實(shí)現(xiàn)線程同步
if (_instance==null)
{
lock (Locker)
{
//Double-Check Locking 雙重檢查鎖定
if (_instance==null)
{
_instance = new Singleton3();
}
}
}
return _instance;
}
}
四、泛型單例模式
代碼:
/// <summary>
/// 泛型單例模式的實(shí)現(xiàn)
/// </summary>
/// <typeparam name="T"></typeparam>
public class GenericSingleton<T> where T : class//,new ()
{
private static T instance;
private static readonly object Locker = new object();
public static T GetInstance()
{
//沒有第一重 instance == null 的話,每一次有線程進(jìn)入 GetInstance()時,均會執(zhí)行鎖定操作來實(shí)現(xiàn)線程同步,
//非常耗費(fèi)性能 增加第一重instance ==null 成立時的情況下執(zhí)行一次鎖定以實(shí)現(xiàn)線程同步
if (instance == null)
{
//Double-Check Locking 雙重檢查鎖定
lock (Locker)
{
if (instance == null)
{
//instance = new T();
//需要非公共的無參構(gòu)造函數(shù),不能使用new T() ,new不支持非公共的無參構(gòu)造函數(shù)
instance = Activator.CreateInstance(typeof(T), true) as T;//第二個參數(shù)防止異常:“沒有為該對象定義無參數(shù)的構(gòu)造函數(shù)?!? }
}
}
return instance;
}