Sometimes there is a need to initialize the singleton class with some helper values. But we can't "publish" a constructor for it. What is the workaround for this?
Attention! overloading the GetInstance or setting a color is not my idea. The color should be set only once. I would like to be sure that MyPainter paints ONLY with the initialized color. Any default color should ever be used.
For more clarity I provide a sample:
''' <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
Thanks.
If you want to initialize it only once upon creation, why not to do that inside the constructor by calling some method, that will pull parameters from somewhere? If this initialization will be called several times - transform it into separate method like setOptions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With