我通常是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/