VB.net实现Singleton模式

在网上搜索了下,VB.net实现singleton的例子还真不多,代码以Java和C#的居多,C++次之,VB最少,偶尔翻到一篇,代码资源耗用可能高了点,Singleton的代码实例都很简单,结合Double-checked locking,在公共代码的基础上修改个lazy  initializtion的代码,关于singleton就不多说了,一个类一个实例,更详细的解释参考GOF 的设计模式一书吧~lazy initializtion实现了用时初始化,也是很有意义的。都说Singleton是概念最简单,最没用,但又最难实现的。呵呵~我也不清楚,没有实践没有发言权。了解下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在底层上的实现细节差异撒卡还弄不清除,不过查到一篇文章说Double checked locking也是线程不安全,更好的方法有待去探索,包括轻量级的Singleton. :)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值