Please review my Singleton class

  • Thread starter Michel van den Berg
  • Start date
M

Michel van den Berg

Hello,

I tried to implement the GoF Singleton Pattern. What do you think?

Public MustInherit Class Singleton(Of T As New)

Public Sub New()
If SingletonCreator.Creating = False Then Throw New
SingletonException(Of T)
End Sub

Public Shared ReadOnly Property Instance() As T
Get
Return SingletonCreator.Instance
End Get
End Property

Private Class SingletonCreator

Private Shared instanceValue As T
Public Shared ReadOnly Property Instance() As T
Get
If instanceValue Is Nothing Then
Creating = True
instanceValue = New T
Creating = False
End If

Return instanceValue
End Get
End Property

Private Shared creatingValue As Boolean = False
Public Shared Property Creating() As Boolean
Get
Return creatingValue
End Get
Set(ByVal value As Boolean)
creatingValue = value
End Set
End Property

End Class
End Class

The client works like:

Public Class SingletonClient
Inherits Singleton(Of SingletonClient)

End Class


That's all! Greetings,

mvb
 
M

Mattias Sjögren

Michel,
I tried to implement the GoF Singleton Pattern. What do you think?

I don't understand the point of the Creating property. It doesn't add
thread safety if that's what you're looking for.

I would add the Class constraint to the generic parameter T since this
only makes sense for reference types.

If you can read C# I strongly recommend you read this page - it
applies to VB as well

http://www.yoda.arachsys.com/csharp/singleton.html


Mattias
 
M

Michel van den Berg

You are right about it not being thread safety (working on that). However,
what it does do is throwing an exception when you try to instantiate the
SingletonClient by calling New SingletonClient().

IMO, this is good practice, which I haven't see in any other singleton class
(why is this?) like the ones described in the url you gave me.
The Creating() property helps the singleton decide if it is being
instantiated using SingletonClient.Instance(), and not by using New
SingletonClient(), as Instance() sets Creating() to true. If I were not to
use this property then I would always get an exception as the singleton
object has to be created in order to instantiate SingletonClient (it will
always reach Singleton.New() and therefore throw the exception).

So, now knowing this, could you please give your advice again, as this is
very welcome!

TIA,

Mvb
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top