vb.net – vb中的单例模式

前端之家收集整理的这篇文章主要介绍了vb.net – vb中的单例模式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我通常是一个c#程序员,但是现在我正在VB中为这个项目工作,当我用来设置一个单例类时,我将遵循Jon Skeet模型
  1. public sealed class Singleton
  2. {
  3. static Singleton instance = null;
  4. static readonly object padlock = new object();
  5.  
  6. Singleton()
  7. {
  8. }
  9.  
  10. public static Singleton Instance
  11. {
  12. get
  13. {
  14. lock (padlock)
  15. {
  16. if (instance == null)
  17. {
  18. instance = new Singleton();
  19. }
  20. return instance;
  21. }
  22. }
  23. }
  24.  
  25. //Added to illistrate the point
  26. public static void a()
  27. {
  28. }
  29.  
  30. public void b()
  31. {
  32. }
  33.  
  34. }

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

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

现在我在VB中做同样的事情

  1. Private Shared _instance As StackTracker
  2. Private Shared ReadOnly _lock As Object = New Object()
  3. Private Sub New()
  4. _WorkingStack = New Stack(Of MethodObject)
  5. _HistoryStack = New Queue(Of MethodObject)
  6. End Sub
  7.  
  8. Public Shared ReadOnly Property Instance() As StackTracker
  9. Get
  10. SyncLock _lock
  11. If (_instance Is Nothing) Then
  12. _instance = New StackTracker()
  13. End If
  14. End SyncLock
  15.  
  16. Return _instance
  17. End Get
  18.  
  19. End Property

我得到StackTracker.Instance.Instance,它一直在继续,而不是世界的尽头,它看起来不错.

问题是VB中存在一种隐藏第二个实例的方式,因此用户无法递归调用Instance?

以下是完整的代码
  1. Public NotInheritable Class MySingleton
  2. Private Shared ReadOnly _instance As New Lazy(Of MySingleton)(Function() New
  3. MySingleton(),System.Threading.LazyThreadSafetyMode.ExecutionAndPublication)
  4.  
  5. Private Sub New()
  6. End Sub
  7.  
  8. Public Shared ReadOnly Property Instance() As MySingleton
  9. Get
  10. Return _instance.Value
  11. End Get
  12. End Property
  13. End Class

然后使用这个类,使用以下方式获取实例:

  1. Dim theSingleton As MySingleton = MySingleton.Instance

猜你在找的VB相关文章