加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

vb.net – vb中的单例模式

发布时间:2020-12-17 00:31:17 所属栏目:大数据 来源:网络整理
导读:我通常是一个c#程序员,但是现在我正在VB中为这个项目工作,当我用来设置一个单例类时,我将遵循Jon Skeet模型 public sealed class Singleton{ static Singleton instance = null; static readonly object padlock = new object(); Singleton() { } public sta
我通常是一个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 illistrate the point
    public static void a()
    {
    }

    public void b()
    {
    }

}

或者现在的变化之一,如果我在c#

Singleton.Instance.什么程序是所有的成员不是静态的,而不是一个.

现在我在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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读