一、前言
单例模式保证一个类在整个程序运行期间,只有一个实例,并提供一个全局访问点。
单例模式的核心要点:构造函数私有化、内部持有唯一实例、对外提供统一访问入口
二、基础的单例实现
非线程安全
vbnet
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
vbnet
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
- 双重检查锁
vbnet
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 只读实例、最简洁安全的写法
vbnet
Public Class Singleton
Public Shared ReadOnly Instance As New Singleton()
Private Sub New()
End Sub
End Class