vb中的单例模式 [英] singleton pattern in vb
问题描述
我通常是一名 c# 程序员,但现在我在 VB 中为这个项目工作,当我用来设置一个单例类时,我会遵循 Jon Skeet 模型
I am normally a c# programmer but am now working in VB for this one project when I use to set up a singleton class I would follow the Jon Skeet model
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# 编写语句
or one of the variations now if I write the statement in c#
Singleton.Instance
什么是所有非静态成员,b而不是a.
Singleton.Instance
What procedures is all of the members that are not static, b but not a.
现在当我在 VB 中做同样的事情时
Now when I do the same in 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
并且它继续运行,虽然它看起来很糟糕,但并不是世界末日.
I get StackTracker.Instance.Instance
and it keeps going, while it is not the end of the world it looks bad.
问题在VB中有没有办法隐藏第二个实例,这样用户就不能递归调用实例?
Question is there a way in VB to hide the second instance so the user can not recursively call 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
然后使用这个类,获取实例使用:
Then to use this class, get the instance using:
Dim theSingleton As MySingleton = MySingleton.Instance
这篇关于vb中的单例模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!