云计算百科
云计算领域专业知识百科平台

VB.NET 中的单例模式

一、前言

单例模式保证一个类在整个程序运行期间,只有一个实例,并提供一个全局访问点。

单例模式的核心要点:构造函数私有化、内部持有唯一实例、对外提供统一访问入口

二、基础的单例实现

非线程安全

Public Class Singleton

Private Shared _instance As Singleton

Private Sub New()
End Sub

Public Shared Function Instance() As Singleton
If _instance Is Nothing Then
_instance = New Singleton()
End If
Return _instance
End Function

End Class

三、线程安全的单例

  • 使用 SyncLock

Public Class Singleton

Private Shared _instance As Singleton
Private Shared ReadOnly _lock As New Object()

Private Sub New()
End Sub

Public Shared ReadOnly Property Instance As Singleton
Get
SyncLock _lock
If _instance Is Nothing Then
_instance = New Singleton()
End If
Return _instance
End SyncLock
End Get
End Property

End Class

  • 双重检查锁

Public Class Singleton

Private Shared _instance As Singleton
Private Shared ReadOnly _lock As New Object()

Private Sub New()
End Sub

Public Shared ReadOnly Property Instance As Singleton
Get
If _instance Is Nothing Then
SyncLock _lock
If _instance Is Nothing Then
_instance = New Singleton()
End If
End SyncLock
End If
Return _instance
End Get
End Property

End Class

  • Shared 只读实例、最简洁安全的写法

Public Class Singleton

Public Shared ReadOnly Instance As New Singleton()

Private Sub New()
End Sub

End Class

赞(0)
未经允许不得转载:网硕互联帮助中心 » VB.NET 中的单例模式
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!