Vb.net 是否可以覆盖新对象的创建并返回现有对象?
下面是我尝试做的一个简单的非工作示例:Vb.net 是否可以覆盖新对象的创建并返回现有对象?,vb.net,Vb.net,下面是我尝试做的一个简单的非工作示例: Public Class repclass Public Shared rep As repclass Public n As Integer Public Sub New(n As Integer) If Not rep Is Nothing Then 'replace me with the existing thing like Me = rep
Public Class repclass
Public Shared rep As repclass
Public n As Integer
Public Sub New(n As Integer)
If Not rep Is Nothing Then
'replace me with the existing thing like
Me = rep
'or
return rep
'or something that actually works here
Else
Me.n = n
rep = Me
End If
End Sub
End Class
这可能吗?我想你想要的是确保一个类只有一个实例的单例设计模式。看见下面是转换为VB的示例:
Public Class Singleton
Private Shared m_instance As Singleton
Private Sub New()
End Sub
Public Shared ReadOnly Property Instance() As Singleton
Get
If m_instance Is Nothing Then
m_instance = New Singleton()
End If
Return m_instance
End Get
End Property
End Class
不需要。谷歌“工厂方法”。(你可能对IoC容器感兴趣。)这个例子被简化了,我确实需要多个实例,但它们在类的参数方面必须是唯一的,但不管怎样都可以工作@JakeFreelander:制作一个字典,添加一个“Get”方法——它将根据传递的参数创建新实例或使用现有实例。