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
相关推荐
海盗12345 小时前
微软技术周报——2026-07-22
microsoft·c#·.net
海盗12345 小时前
微软技术日报 ——2026-07-21
microsoft·c#·.net
半亩码田6 小时前
【.NET新特性·第8篇】.NET 9 AI 构建基块:Microsoft.Extensions.AI
人工智能·microsoft·.net
Ctrl+Z侠1 天前
.NET WebApi Windows / Linux Docker 全链路压测与瓶颈定位 0 到 1 教程
linux·windows·.net
慧都小妮子1 天前
Aspose.CAD for .NET 26.6 更新发布
pdf·.net·3d渲染·cad·pdf导出·ifc编辑
张小姐的猫1 天前
【Linux】网络编程 —— HTTP协议(上)
linux·运维·服务器·网络·http·单例模式·策略模式
夜莺悠吟1 天前
关于对 C# 中 ImplicitUsings,GlobalUsings 的讨论
c#·.net
zjun10011 天前
C++:单例模式
c++·单例模式