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
相关推荐
彭波3961 天前
.NET Framework 3.5问题修复教程!可以离线修复
windows·安全·电脑·.net·开源软件
武藤一雄1 天前
WPF处理耗时操作的7种方法
microsoft·c#·.net·wpf
武藤一雄1 天前
C#常见面试题100问 (第一弹)
windows·microsoft·面试·c#·.net·.netcore
江沉晚呤时1 天前
.NET 9 快速上手 RabbitMQ 直连交换机:高效消息传递实战指南
开发语言·分布式·后端·rabbitmq·.net·ruby
摆烂的少年2 天前
Asp .net web应用程序使用VS2022调试时打开文件选择器服务自动关闭问题
c#·.net
.NET修仙日记2 天前
构建社区照护桥梁:.NET Core3.1+MVC社区呼叫系统设计与实现
c#·毕业设计·.net·.net core·社区照护平台
波波0072 天前
每日一题:.NET 中的“反射”是什么?
开发语言·.net
qq_410194292 天前
.net性能优化的步骤,前端、后端、数据库
性能优化·.net
似水明俊德2 天前
04-C#.Net-委托和事件-面试题
java·开发语言·面试·c#·.net
步步为营DotNet2 天前
探索.NET 11 中Semantic Kernel在智能客户端应用的创新实践
.net