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
相关推荐
2601_9620725513 小时前
李梦娇常识4600问|题库|打印版
sql·华为od·华为·c#·华为云·.net·harmonyos
步步为营DotNet1 天前
基于.NET Aspire 实现云原生应用的高效监控与可观测性
云原生·.net·wpf
咸鱼翻身小阿橙1 天前
VS2008 + .NET3.5 环境、加热台TCP通讯场景
tcp/ip·php·.net
tonydf2 天前
DotNet项目接入Copilot SDK简单案例
后端·.net·github copilot
ABprogramming2 天前
Aspire入门指南
c#·.net
User_芊芊君子2 天前
鸿蒙PC适配:Pinta GTK 图像编辑器鸿蒙 PC ArkWeb 适配全记录:从 .NET_GTK4 桌面到 HarmonyOS PC HAP
编辑器·.net·harmonyos
ServBay2 天前
你跟高级 C# 工程师的区别,就是这8个开发技巧
后端·c#·.net
重生之我是Java开发战士3 天前
【Java SE】多线程(三):单例模式,阻塞队列,线程池与定时器
java·javascript·单例模式
小满Autumn3 天前
log4net 日志框架 — 从配置到实战速查手册
笔记·c#·.net·wpf·上位机·log4net