I'm in the process of writing a session wrapper class. It's purpose is to ensure that all objects placed into session be serializable. When it is complete I will be sure to post the code on my blog.
It soon became apparent that this session wrapper needed to be implemented as a singleton. Why not make use of generics and create a generic singleton. The listing below is a VB.NET implementation of a singleton that can be used for any class.
Listing 1: Singleton using Generics
'Constraints ensuring that the type will be a class and has a constructor.
Public Class Singleton(Of T As {New, Class})
'Property to return a single instance of the type
Private Shared ReadOnly _instance As New T
Public Shared ReadOnly Property Instance() As T
Get
Return _instance
End Get
End Property
'Cannot directly instantiate the class
Private Sub New()
End Sub
End Class
With the exception of generics, this is a typical .NET implementation of a singleton. Note that the constraints ensure that only types that are classes and have a constructor can be used.
Listing 2 shows how to take a plain class and implement it as a singleton using the above code.
Listing 2: Making use of the Generic Singleton
Singleton(Of Foobar).Instance.foo()
Public Class Foobar
Sub New()
End Sub
Public Sub foo()
End Sub
End Class
In the code example above the class Foobar can be instantiated on it's own. If you would like to restrict how it is created (i.e., it can only be created in the context of the singleton) then package the singleton and the class Foobar into a seperate library and mark Foobar's constructor as Friend.
Guess the movie
You guys give up yet? Or are you thirsty for more?