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