面試官問(wèn):你知道 C# 單例模式有哪幾種常用的實(shí)現(xiàn)方式?
單例模式介紹
單例模式是一種創(chuàng)建型設(shè)計(jì)模式,它主要確保在一個(gè)類只有一個(gè)實(shí)例,并提供一個(gè)全局訪問(wèn)點(diǎn)來(lái)獲取該實(shí)例。在C#中,有多種方式實(shí)現(xiàn)單例模式,每種方式都有其特定的使用場(chǎng)景和注意事項(xiàng)。
設(shè)計(jì)模式的作用
設(shè)計(jì)模式是對(duì)面向?qū)ο笤O(shè)計(jì)中反復(fù)出現(xiàn)的問(wèn)題的解決方案。它們提供了被反復(fù)使用、多數(shù)人知曉的、經(jīng)過(guò)分類編目的代碼設(shè)計(jì)經(jīng)驗(yàn)總結(jié)。
- 提高代碼的可重用性:通過(guò)定義一套標(biāo)準(zhǔn)的解決方案,設(shè)計(jì)模式使得相同或類似的問(wèn)題可以在不同的項(xiàng)目中復(fù)用相同的代碼結(jié)構(gòu)或邏輯。
- 增強(qiáng)代碼的可讀性:設(shè)計(jì)模式使用清晰、簡(jiǎn)潔的方式表達(dá)復(fù)雜的代碼邏輯,使得其他開發(fā)者能夠更容易地理解和維護(hù)代碼。
- 提高系統(tǒng)的可維護(hù)性:設(shè)計(jì)模式遵循一定的設(shè)計(jì)原則,如開閉原則、里氏代換原則等,這些原則有助于降低系統(tǒng)各部分的耦合度,提高系統(tǒng)的可擴(kuò)展性和可維護(hù)性。
餓漢式單例模式
餓漢式單例是在類加載時(shí)就創(chuàng)建實(shí)例。優(yōu)點(diǎn)是實(shí)現(xiàn)簡(jiǎn)單,缺點(diǎn)是如果該實(shí)例不被使用會(huì)造成資源浪費(fèi)。
/// <summary>
/// 餓漢式單例模式
/// </summary>
public class SingletonEager
{
private SingletonEager() { }
private static readonly SingletonEager _instance = new SingletonEager();
public static SingletonEager Instance
{
get { return _instance; }
}
public void DoSomething()
{
Console.WriteLine("餓漢式單例模式.");
}
}
懶漢式單例模式
懶漢式單例在第一次被訪問(wèn)時(shí)才創(chuàng)建實(shí)例。為了線程安全,通常需要使用鎖機(jī)制。
/// <summary>
/// 懶漢式單例模式
/// </summary>
public class SingletonLazy
{
private SingletonLazy() { }
private static SingletonLazy? _instance;
private static readonly object _lockObj = new object();
public static SingletonLazy Instance
{
get
{
if (_instance == null)
{
lock (_lockObj)
{
if (_instance == null)
{
_instance = new SingletonLazy();
}
}
}
return _instance;
}
}
public void DoSomething()
{
Console.WriteLine("懶漢式單例模式.");
}
}
懶加載單例模式
如果您使用的是 .NET 4(或更高版本),可以使用Lazy<T>
類來(lái)實(shí)現(xiàn)線程安全的懶加載單例模式。
/// <summary>
/// 懶加載單例模式
/// </summary>
public sealed class SingletonByLazy
{
private static readonly Lazy<SingletonByLazy> _lazy = new Lazy<SingletonByLazy>(() => new SingletonByLazy());
public static SingletonByLazy Instance { get { return _lazy.Value; } }
private SingletonByLazy() { }
public void DoSomething()
{
Console.WriteLine("懶加載單例模式.");
}
}