Sometimes it becomes necessary to initialize a singleton class with some auxiliary values. But we cannot "publish" the constructor for it. What is the workaround for this?
Attention! overloading GetInstance or setting color is not my idea. Color should be set only once. I would like to be sure that MyPainter draws ONLY with initialized color. Use any color by default .
For 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.
source
share