VB.NET实现Singleton模式

Singleton模式:一个类只会创建一个实例。

下面的代码用VB.NET实现了Singleton模式:
ExpandedBlockStart.gif ContractedBlock.gif Public   Class Singleton Class Singleton
InBlock.gif
InBlock.gif    
Private Shared _Singleton As Singleton
InBlock.gif
InBlock.gif    
Private Shared _Mutex As New System.Threading.Mutex '同步基元也可用于进程间同步
InBlock.gif

ExpandedSubBlockStart.gifContractedSubBlock.gif    
Private Sub New()Sub New()
InBlock.gif
ExpandedSubBlockEnd.gif    
End Sub

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
Public Shared Function GetInstance()Function GetInstance() As Singleton
InBlock.gif
InBlock.gif        _Mutex.WaitOne() 
'当在派生类中重写时,阻塞当前线程,直到当前的 System.Threading.WaitHandle 收到信号
InBlock.gif

InBlock.gif        
Try
InBlock.gif            
If _Singleton Is Nothing Then
InBlock.gif                _Singleton 
= New Singleton
InBlock.gif            
End If
InBlock.gif
InBlock.gif        
Finally
InBlock.gif            _Mutex.ReleaseMutex() 
'释放 System.Threading.Mutex 一次
InBlock.gif
        End Try
InBlock.gif
InBlock.gif        
Return _Singleton
InBlock.gif
ExpandedSubBlockEnd.gif    
End Function

InBlock.gif
ExpandedBlockEnd.gif
End Class
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值