Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.
Use Singletonprovider instead of the Singleton pattern
From Wiki
We all know the singleton pattern for VB.NET. The singleton pattern is probably the most ised and overused pattern there is, but I won't go into that.
For those of you who forgot. This is a threadsafe singleton implementation.
- Public Class Class1
- #Region " Singleton Pattern Support "
- ''' <summary>
- ''' Object to make it threadsafe
- ''' </summary>
- ''' <remarks></remarks>
- Private Shared _SyncRoot As New Object
- ''' <summary>
- ''' Object that holds an instance of this class
- ''' </summary>
- ''' <remarks></remarks>
- Private Shared _Instance As Class1
- ''' <summary>
- ''' Make the constructor private so the have to use then Instance property to get an instance of this class
- ''' </summary>
- ''' <remarks></remarks>
- Private Sub New()
- End Sub
- ''' <summary>
- ''' Returns an Instance of this class
- ''' </summary>
- ''' <value></value>
- ''' <returns>An instance of class1</returns>
- ''' <remarks></remarks>
- Public Shared ReadOnly Property Instance() As Class1
- Get
- SyncLock _SyncRoot
- If _Instance Is Nothing Then
- _Instance = New Class1
- End If
- Return _Instance
- End SyncLock
- End Get
- End Property
- #End Region
- End Class
But this adds extra code to your class. And this is something to I would avoid. And Do we always need the same instance of this class? Perhaps it could change in the future. So I like the use of singleton provider better.
This is what it looks like
- Public Class SingletonProvider(Of itemtype As {New})
- Public Sub New()
- End Sub
- Public Shared ReadOnly Property Instance() As itemtype
- Get
- Return SingletonCreator.instance
- End Get
- End Property
- Class SingletonCreator
- Shared Sub New()
- End Sub
- Public Shared ReadOnly instance As itemtype = New itemtype()
- End Class
- End Class
This piece of code comes from [1].
I won't even try to explain it. But if you want to use it you have to make sure your singleton class has a default constructor
This is how you use it
- Singletonprovider(Of Class1).Instance.UseMethod
I hope that was usefull?



LTD Social Sitings
Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.