VB.NET Singleton具體實現(xiàn)方法解析
VB.NET編程中有一種叫做Singleton的模式,它的影音方法簡單靈活,可以幫助開發(fā)人員輕松的解決相關(guān)問題。那么如何才能正確的實現(xiàn)應(yīng)用VB.NET Singleton這一模式呢?在這里就為大家詳細(xì)介紹一下。
在網(wǎng)上搜索了下,VB.NET Singleton實現(xiàn)的例子還真不多,代碼以Java和C#的居多,C++次之,vb最少,偶爾翻到一篇,代碼資源耗用可能高了點,Singleton的代碼實例都很簡單,結(jié)合Double-checked locking,在公共代碼的基礎(chǔ)上修改個lazy initializtion的代碼,關(guān)于singleton就不多說了,一個類一個實例,更詳細(xì)的解釋參考GOF 的設(shè)計模式一書吧~lazy initializtion實現(xiàn)了用時初始化,也是很有意義的。都說Singleton是概念最簡單,最沒用,但又最難實現(xiàn)的。呵呵~我也不清楚,沒有實踐沒有發(fā)言權(quán)。了解下VB.NET Singleton,為日后學(xué)習(xí)設(shè)計模式打下基礎(chǔ)也是很有必要的。
- public Class Singleton
- private shared _Singleton as singleton = nothing
- private shared _Mutex as new system.threading.Mutex '進(jìn)程同步
- private sub new ()
- '類構(gòu)造
- end sub
- public shared function Instance () as singleton
- if _singleton is nothing then 'double-checked locking
- _mutex.waitone()
- try
- if _singleton is nothing then
- _singleton = new singleton
- end if
- finally
- _mutex.releaseMutex()
- end try
- end if
- return _singleton
- end function
- end class
代碼中mutex被聲明成Shared,如果是非shared,需要通過獲取實例的方法調(diào)用mutex的方法,SIngleton.instance._mutex.waitone(), .net Framework和Jvm在底層上的實現(xiàn)細(xì)節(jié)差異撒卡還弄不清除,不過查到一篇文章說Double checked locking也是線程不安全,更好的方法有待去探索,包括輕量級的VB.NET Singleton. :)
【編輯推薦】