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
相关推荐
ChaITSimpleLove2 小时前
.NET 10 的 AI 技术栈全景:M.E.AI、MCP 与 Agent Framework 深度解析
人工智能·.net·ai agent·mcp·agent framework·m.e.ai·hosted agents
旧梦95273 小时前
Java 单例模式:从基础到实战的完整指南
java·开发语言·单例模式
数据知道8 小时前
.NET 反序列化漏洞——ViewState 与 BinaryFormatter 实战深度剖析
网络·网络安全·.net
码匠许师傅12 小时前
【设计模式精讲】4.单例模式(Singleton)
c++·单例模式·设计模式
leonkay21 小时前
C# 特性(Attribute)——【1】基础讲解
开发语言·青少年编程·面试·c#·.net·个人开发
界面开发小八哥1 天前
界面控件DevExpress WinForms中文帮助文档 - 将基于DevExpress的.NET Framework应用迁移至最新版.NET
ui·.net·界面控件·winform·devexpress·ui开发
人丰1 天前
血泪复盘:一次由 HttpContext.Current 引发的 CPU 100% 惨案
性能优化·.net
ChaITSimpleLove1 天前
用 .NET 10 技术栈 “玩转 AI 学习” 的路线图:从 Minimal API 到 AI Agent 产品
人工智能·.net·学习 ai
米啦啦.2 天前
设计模式/
观察者模式·单例模式·设计模式·工厂模式
半亩码田2 天前
【.NET新特性·第14篇】.NET 10 运行时与 SDK 新特性
.net