Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to initialize a Singleton?

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.

like image 305
serhio Avatar asked Dec 30 '25 08:12

serhio


1 Answers

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.

like image 136
Vladislav Rastrusny Avatar answered Jan 02 '26 08:01

Vladislav Rastrusny