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