Thursday, November 20, 2003

Singleton Pattern


Description

I once saw this pattern summarized as "There is only one Elvis and there will only ever be one Elvis". The Singleton is a pattern that is used when you want one and only one instance of an object.

The usual reasons for this are: the object encapsulates an important resource that is used in many places (for example if you don't want an application to be able to open up several connections to the database make a singleton out of the database connection), or the resource can only be used by one thread at a time (e.g., a class that plays a song file. You only want one song playing at a time.)

Example

The usual way this is implemented is by
1) declare a private static (shared in VB) variable to reference the single instance,
2) create a static method in the singleton class that returns the single instance
3) make the constructor private so the class can only be instantiated by itself.

Here is an example:


Public Class SingletonMP3Player
'1) the private variable
Private Shared _instance As SingletonMP3Player
 
'2) the static method to return the singleton
Public Shared Function GetInstance() As SingletonMP3Player
'if it has not already been instantiated then create it
If _instance Is Nothing Then
_instance = New SingletonMP3Player
End If
Return _instance
End Function
 
'3) the private constructor
Private Sub New()
'prevents instantiation from outside the class
End Sub
 
'Other methods required to make the class useful
Public Sub Play(filename As String)
'code to play, stopping self if already playing something else
End Sub
 
Public Sub StopPlaying()
'code here
End Sub
 
Public Sub OtherUserfulMethod()
'etc ...
End Sub
End Class


Here is how you could use it:


Public Class Singing
Sub SingTheBlues()
Dim myPlayer As SingletonMP3Player
myPlayer = SingletonMP3Player.GetInstance()
myPlayer.Play("c:\music\blues\Born Under A Bad Sign.mp3")
End Sub
 
Sub GrowlDemonically()
Dim myPlayer As SingletonMP3Player
myPlayer = SingletonMP3Player.GetInstance()
myPlayer.Play("c:\music\deathmetal\Blackwater Park.mp3")
End Sub
 
'or a show off way to do it
Sub JustListen()
SingletonMP3Player.GetInstance().Play("c:\music\prog\3 Min Warning.mp3")
End Sub
End Class

Resources

Wikipedia - Singleton pattern
Data & Object Factory - Singleton
DotNetExtreme - Singleton pattern

No comments: