基于靜態(tài)Singleton模式的使用介紹
什么是靜態(tài)單例模式?
靜態(tài)單例模式(Static Singleton Pattern)是我在實(shí)踐中總結(jié)的模式,主要解決的問題是在預(yù)先知道某依賴項(xiàng)為單例應(yīng)用時(shí),通過靜態(tài)緩存該依賴項(xiàng)來提供訪問。當(dāng)然,解決該問題的辦法有很多,這只是其中一個(gè)。
實(shí)現(xiàn)細(xì)節(jié)
/// <summary>
/// 靜態(tài)單例
/// </summary>
/// <typeparam name="TClass">單例類型</typeparam>
public static class Singleton<TClass> where TClass : class, new()
{
private static readonly object _lock = new object();
private static TClass _instance = default(TClass);
/// <summary>
/// 獲取單例實(shí)例
/// </summary>
public static TClass GetInstance()
{
return Instance;
}
/// <summary>
/// 單例實(shí)例
/// </summary>
public static TClass Instance
{
get
{
if (_instance == null)
{
lock (_lock)
{
if (_instance == null)
{
_instance = new TClass(); // must be public constructor
}
}
}
return _instance;
}
}
/// <summary>
/// 設(shè)置單例實(shí)例
/// </summary>
/// <param name="instance">單例實(shí)例</param>
public static void Set(TClass instance)
{
lock (_lock)
{
_instance = instance;
}
}
/// <summary>
/// 重置單例實(shí)例
/// </summary>
public static void Reset()
{
lock (_lock)
{
_instance = default(TClass);
}
}
}
應(yīng)用測試
class Program
{
interface IInterfaceA
{
string GetData();
}
class ClassA : IInterfaceA
{
public string GetData()
{
return string.Format("This is from ClassA with hash [{0}].", this.GetHashCode());
}
}
static void Main(string[] args)
{
string data1 = Singleton<ClassA>.GetInstance().GetData();
Console.WriteLine(data1);
string data2 = Singleton<ClassA>.GetInstance().GetData();
Console.WriteLine(data2);
Console.ReadKey();
}
}
測試結(jié)果
- .Net 單例模式(Singleton)
- 五種單件模式之Singleton的實(shí)現(xiàn)方法詳解
- C#多線程Singleton(單件)模式模板
- php設(shè)計(jì)模式 Singleton(單例模式)
- javascript 單例/單體模式(Singleton)
- .NET c# 單體模式(Singleton)
- Python設(shè)計(jì)模式之單例模式實(shí)例
- Python設(shè)計(jì)模式之觀察者模式實(shí)例
- Python設(shè)計(jì)模式之代理模式實(shí)例
- python中g(shù)etattr函數(shù)使用方法 getattr實(shí)現(xiàn)工廠模式
- Windows 配置Apache以便在瀏覽器中運(yùn)行Python script的CGI模式
- Python下singleton模式的實(shí)現(xiàn)方法
相關(guān)文章
詳解WPF雙滑塊控件的使用和強(qiáng)制捕獲鼠標(biāo)事件焦點(diǎn)
這篇文章主要為大家詳細(xì)介紹了WPF中雙滑塊控件的使用和強(qiáng)制捕獲鼠標(biāo)事件焦點(diǎn)的實(shí)現(xiàn),文中的示例代碼講解詳細(xì),感興趣的可以嘗試一下2022-07-07舊項(xiàng)目升級(jí)新版Unity2021導(dǎo)致Visual?Studio無法使用的問題
在項(xiàng)目開發(fā)過程中,不可避免的會(huì)升級(jí)開發(fā)工具。這次我在舊項(xiàng)目版本升級(jí)到新版Unity2021.2.x時(shí),出現(xiàn)Visual?Studio無法定位等問題,這里我給大家分享下解決方法,舊項(xiàng)目升級(jí)新版Unity2021導(dǎo)致Visual?Studio無法使用的問題,需要的朋友可以參考下2021-12-12C# VB 實(shí)現(xiàn)10進(jìn)制 16進(jìn)制之間互相轉(zhuǎn)換
如何將10進(jìn)制轉(zhuǎn)成16進(jìn)制,又如何將16進(jìn)制數(shù)轉(zhuǎn)成10進(jìn)制,本文將介紹C#和VB實(shí)現(xiàn)代碼,需要了解的朋友可以參考下2012-11-11C#實(shí)例化和靜態(tài)類對象調(diào)用對比
這篇文章主要介紹了C#實(shí)例化和靜態(tài)類對象調(diào)用對比,什么時(shí)候用實(shí)例化對象,什么時(shí)候用靜態(tài)類對象,內(nèi)存和生命周期又是如何,框架本身的回收機(jī)制是什么,下文詳細(xì)解說需要的小伙伴可以參考一下2022-04-04WPF實(shí)現(xiàn)帶模糊搜索的DataGrid的示例代碼
這篇文章主要為大家詳細(xì)介紹了WPF如何實(shí)現(xiàn)帶模糊搜索的DataGrid,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,需要的可以參考一下2023-02-02