Singleton Pattern

From REALbasicWiki

Jump to: navigation, search

Contents

[edit] Intention

The singleton pattern ensures that in an application there is only one instance of a class existing. Thus after the first initialization subsequent calls to a class that implements the singleton pattern only get a reference to the original instance.

[edit] Class-Diagram

Image:Singleton.png

[edit] Example

The secret of the Singleton is the fact that its constructor is private. Thus it cannot be instantiated from without. Every caller that needs to get an instance of the Singleton has to call its shared method getInstance() instead. Also there must be a way to store the instance of the Singleton. This is achieved by adding a shared property of type Singleton. When the method getInstance() is called, it first checks if there is already a Singleton-instance existing. If not it calls the constructor (which is possible from within the class). Anyway it then gives back the reference to the instance.

In our example there is another shared property that stores the number of calls for a new instance.


Class Singleton

Private Sub Constructor()
noOfCallers = 0
End Sub

Shared Function getInstance() As Singleton
if instance = nil then
instance = new Singleton
end if
noOfCallers = noOfCallers + 1
return instance
End Function

Function toString() As String
dim s as string
s = "Until now there were " + str(noOfCallers) + " calls to get an instance of me. But I am unique :)."
return s
End Function

Private Shared instance As Singleton
Private Shared noOfCallers As Integer

End Class

Try it out: Put this code into the action-event of a Pushbutton.


dim s as Singleton
s = Singleton.getInstance
MsgBox s.toString

As you will see every time you push the button the messagebox will show the current number of calls to the instance...

[edit] Another Example


Class Singleton

Private Sub Constructor()
//the existence of this private constructor prevents instantiation outside the class
End Sub

Shared Function GetInstance() As Singleton
static theInstance as Singleton = new Singleton
return theInstance
End Function

End Class

[edit] External resources

http://en.wikipedia.org/wiki/Singleton_pattern

For more information about the Unified Modeling Language that was used to describe the classes please visit these links:

http://www.holub.com/goodies/uml/index.html

http://www.developer.com/design/article.php/2206791

http://en.wikipedia.org/wiki/Unified_Modeling_Language

Personal tools
related