C#實(shí)現(xiàn)單件模式的三種常用方法
更新時(shí)間:2015年04月02日 14:45:41 作者:令狐不聰
這篇文章主要介紹了C#實(shí)現(xiàn)單件模式的三種常用方法,分析了單件模式的原理、功能與常用的三種實(shí)現(xiàn)方法,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
本文實(shí)例講述了C#實(shí)現(xiàn)單件模式的三種常用方法。分享給大家供大家參考。具體分析如下:
單件模式是一種設(shè)計(jì)模式,即保持同時(shí)只能創(chuàng)建一個(gè)實(shí)例,下面列出了C#實(shí)現(xiàn)單件模式的三種方法
方法1
public sealed Class Singleton
{
private static ReadOnly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance
{
get
{
return instance;
}
}
}
方法2
public sealed Class ClassicSingleton
{
private static ClassicSingleton instance;
private static object SyncRoot = new Object ();
private ClassicSingleton(){}
public static ClassicSingleton Instance
{
get
{
if(instance == null)
{
lock (SyncRoot)
{
if(instance == null)
{
instance = new ClassicSingleton ();
}
}
}
return instance;
}
}
}
方法3
public Class Singleton
{
private static Singleton instance;
// Added a static mutex for synchronising use of instance.
private static System.Threading.Mutex mutex;
private Singleton(){}
static Singleton ()
{
instance = new Singleton();
mutex = new System.Threading.Mutex();
}
public static Singleton Acquire()
{
mutex.WaitOne ();
return instance;
}
// Each call to Acquire () requires a call to Release()
public static void Release()
{
mutex.ReleaseMutex();
}
}
希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助。
您可能感興趣的文章:
- C++設(shè)計(jì)模式之職責(zé)鏈模式
- php設(shè)計(jì)模式 Chain Of Responsibility (職責(zé)鏈模式)
- C#組合模式實(shí)例詳解
- C#命令模式用法實(shí)例
- C#中單例模式的三種寫(xiě)法示例
- 淺談C#設(shè)計(jì)模式之工廠模式
- 淺談C#設(shè)計(jì)模式之代理模式
- 淺談C#設(shè)計(jì)模式之開(kāi)放封閉原則
- 淺談c#設(shè)計(jì)模式之單一原則
- C#設(shè)計(jì)模式之單例模式實(shí)例講解
- C#設(shè)計(jì)模式之觀察者模式實(shí)例講解
- C#職責(zé)鏈模式實(shí)例詳解
相關(guān)文章
C#實(shí)現(xiàn)打開(kāi)指定目錄和指定文件的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何利用C#實(shí)現(xiàn)打開(kāi)指定目錄、打開(kāi)指定目錄且選中指定文件、打開(kāi)指定文件,感興趣的小伙伴可以嘗試一下2022-06-06
C#幾種獲取網(wǎng)頁(yè)源文件代碼的實(shí)例
C#幾種獲取網(wǎng)頁(yè)源文件代碼的實(shí)例,需要的朋友可以參考一下2013-04-04
C#實(shí)現(xiàn)子類與父類的相互轉(zhuǎn)換
這篇文章主要介紹了C#實(shí)現(xiàn)子類與父類的相互轉(zhuǎn)換,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05
winform實(shí)現(xiàn)可拖動(dòng)的自定義Label控件
這篇文章主要為大家詳細(xì)介紹了winform實(shí)現(xiàn)可拖動(dòng)的自定義Label控件,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-03-03

