Singleton Design Pattern
The Singleton design pattern is probably the simplest of all the common design patterns. Its purpose is also simple: to ensure that only once instance of a class is ever instantiated.
You might be thinking that you could just use a module for this purpose. A module is close to a singleton, but since it is not a class it is never actually instantiated at all. This means you cannot easily have any startup code that runs the first time it is used.
Like modules, singletons should be used judiciously. Too many of them probably indicates a flaw in your design.
However, a singleton does have its uses. Occasionaly you might have something that needs to exist only once and will in fact be jeopardized if it is accessed from multiple instances.
An example would be a preference class. There should be only one set of preferences. It would be bad if two different instances of a preference class had different values.
Before Shared methods were added to the language, you could not easily create “true” singleton class in REALbasic. With the latest releases of REALbasic, it is pretty easy.
Create a new class and call it MySingleton. The first thing to do is create a protected constructor for this class. A protected constructor prevents anyone from instantiating the class. So you’ve effectively just created a class that can never be instantiated, so it’s not too useful yet.
So how can we get an instance? We’ll add a new method whose only purpose is to return an instance of the class. This method will be smart. If an instance has already been created it will return the existing one. If one has not been created, then it will create one and return that. We’ll store this instance in a private shared property.
But how can we call the method if we can’t get an instance of the class to begin with? Seems like a catch-22. And it was until Shared Methods were added to REALbasic. So go ahead and add this property and Public Shared Method to the class (Project->Add->Shared Method):
Private Shared instance As MySingleton Public Function GetInstance Returns MySingleton If instance Is Nil Then instance = New MySingleton End If Return instance End Function
You now have a singleton class. Usage is simple:
Dim singleton As MySingleton singleton = MySingleton.GetInstance
