VB.NET 中的单例模式

一、前言

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

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

二、基础的单例实现

非线程安全

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
相关推荐
1-1=013 小时前
.NET Core 文件系统
.net·.netcore·1024程序员节
IsITGirl13 小时前
VMware Fusion(Mac)Windows ARM 虚拟机 NAT (vmnet8) 报错解决记录
windows·macos·.net·桥接模式
学以智用1 天前
WinForms / WPF / Blazor 项目模板详解
.net
1-1=01 天前
.NET Core 内存管理
.net·.netcore
无风听海2 天前
.NET 10之Span技术总结
.net
1-1=02 天前
.NET Core 配置与选项
.net·.netcore·1024程序员节
mudtools2 天前
在飞书 SDK 上用 Microsoft Agent Framework 搭一个能干活的工作搭子
人工智能·ai·.net·飞书·agent
ChaITSimpleLove2 天前
Layout.WatchDog.NET 1.5.0-beta.3 发布:统一全后端雪花 ID 策略,数据库能力矩阵一览
.net·watchdog·日志记录器·节点资源监控看板·.net专属轻量级日志中心
IT规划师2 天前
MQTT 实战 - 放下炫技,8 年踩坑的真心话与方法论(收官)
物联网·.net