vb.net - vb中的单例模式

标签 vb.net singleton

我通常是C#程序员,但现在在VB中为这个项目工作,当我用来设置单例类时,我将遵循Jon Skeet模型

public sealed class Singleton
{
    static Singleton instance = null;
    static readonly object padlock = new object();

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }

    //Added to illustrate the point
    public static void a()
    {
    }

    public void b()
    {
    }

} 


或现在的一种变体,如果我用C#编写语句

Singleton.Instance哪些程序不是b,但不是a的所有静态成员。

现在,当我在VB中执行相同操作时

Private Shared _instance As StackTracker
Private Shared ReadOnly _lock As Object = New Object()
Private Sub New()
    _WorkingStack = New Stack(Of MethodObject)
    _HistoryStack = New Queue(Of MethodObject)
End Sub

Public Shared ReadOnly Property Instance() As StackTracker
    Get
        SyncLock _lock
            If (_instance Is Nothing) Then
                _instance = New StackTracker()
            End If
        End SyncLock

        Return _instance
    End Get

End Property


我得到StackTracker.Instance.Instance并且它继续前进,虽然这不是世界末日,但它看起来很糟糕。

问题在VB中是否有隐藏第二个实例的方法,以便用户无法递归调用Instance?

最佳答案

这是完整的代码:

Public NotInheritable Class MySingleton
    Private Shared ReadOnly _instance As New Lazy(Of MySingleton)(Function() New
        MySingleton(), System.Threading.LazyThreadSafetyMode.ExecutionAndPublication)

    Private Sub New()
    End Sub

    Public Shared ReadOnly Property Instance() As MySingleton
        Get
            Return _instance.Value
        End Get
    End Property
End Class


然后使用此类,使用以下方法获取实例:

Dim theSingleton As MySingleton = MySingleton.Instance

关于vb.net - vb中的单例模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3319108/

相关文章:

java - 使用 Wildfly 进行集群单例?

c++ - 陷阱 : The static stack variable Singleton class

vb.net - 创建透明控件的一般解决方案是什么?

vb.net - rdlc CountDistinct 其中状态 = 1

c# - .Net 可折叠面板或可折叠链接控件

java - 免费延迟初始化

java - 静态类 vs 单例类

c# - 这真的是单例吗?

arrays - 删除数组——有必要吗?

database - 我想知道当我销售我的软件时我有哪些 DBMS 选项