有时需要用一些辅助值来初始化单例类。但是我们不能为它“发布”一个构造函数。解决方法是什么?
注意! 重载 GetInstance 或设置颜色不是我的主意。颜色应该只设置一次。我想确保 MyPainter 使用初始化颜色绘制ONLY。 任何默认颜色都应该使用。
为了更清楚,我提供了一个示例:
''' <summary>
''' Singleton class MyPainter
''' </summary>
Public Class MyPainter
Private Shared _pen As Pen
Private Shared _instance As MyPainter = Nothing
Private Sub New()
End Sub
''' <summary>
''' This method should be called only once, like a constructor!
''' </summary>
Public Shared Sub InitializeMyPainter(ByVal defaultPenColor As Color)
_pen = New Pen(defaultPenColor)
End Sub
Public Shared Function GetInstance() As MyPainter
If _instance Is Nothing Then
_instance = New MyPainter
End If
Return _instance
End Function
Public Sub DrawLine(ByVal g As Graphics, ByVal pointA As Point, ByVal pointB As Point)
g.DrawLine(_pen, pointA, pointB)
End Sub
End Class
谢谢。
最佳答案
如果你只想在创建时初始化它一次,为什么不通过调用某些方法在构造函数中执行此操作,这将从某处提取参数?如果此初始化将被多次调用 - 将其转换为单独的方法,如 setOptions。
关于.net - 如何初始化单例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1687387/