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
相关推荐
用户298698530142 天前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
牧马人win2 天前
SmartDapper.Repository
.net
mudtools3 天前
搭建一套.net下能落地的飞书考勤系统
后端·c#·.net
玩泥巴的3 天前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书
快乐非自愿4 天前
C# 中的 Span 和内存:.NET 中的高性能内存处理
java·c#·.net
Traced back4 天前
【.NET7 WinForm 实战】三层架构+EF Core+多数据库+完整功能(源码+教程+脚本)
数据库·架构·.net
波波0075 天前
每日一题:IEnumerable和IQueryable区别?
.net·面试题
light blue bird5 天前
产线多并发客户端指令操作场景组件
jvm·oracle·.net·winform