Duplicate Singletons

BlitzMax Forums/BlitzMax Programming/Duplicate Singletons

Macguffin(Posted 2008) [#1]
I was reading about singletons, and curious what BlitzMax supports. Found one thread from a couple months ago where people were creating singletons with Create().

My question: is there any way to stop someone from just doing:

Local newCreate:TSingleton = New TSingleton


and creating a second instance?


Brucey(Posted 2008) [#2]
You can throw an assert in the New() method if an instance alread exists.
Type Singleton
  Global instance:Singleton

  Method New()
    Assert instance, "An instance already exists..."
    instance = Self
  End Method
End Type



Muttley(Posted 2008) [#3]
This is the template I use for Singletons. ziggy is also going to be adding this as one of the built in Code Templates in BLIde in a next version.

Type TSingleton

	Global instance:TSingleton		' This holds the singleton instance of this Type

	Method New()
		If instance Throw "Cannot create multiple instances of Singleton Type"
	EndMethod

	Function Create:TSingleton()
		Return TSingleton.GetInstance()
	End Function
	
	Function GetInstance:TSingleton()
		If Not instance
			Return New TSingleton
		Else
			Return instance
		EndIf
	EndFunction
	
EndType



Difference(Posted 2008) [#4]
or even
Type TSingleton

	Global instance:TSingleton = New TSingleton		' This holds the singleton instance of this Type

	Method New()
		If instance Throw "Cannot create multiple instances of Singleton Type"
	EndMethod
	
	Function GetInstance:TSingleton()
		Return instance
	EndFunction
	
EndType



Macguffin(Posted 2008) [#5]
Ah! Thanks - I was under the impression you couldn't override New(). Reviewing it, I was just recalling that it can't accept parameters.


ziggy(Posted 2008) [#6]
@Muttley: Found a bug in the singleton class. You can create several instances of a class if not using the create function (just New)
I've changed to this:
Type TSingleton

	Global instance:TSingleton		' This holds the singleton instance of this Type
		
'#Region Constructors
	Method New()
		If instance Throw "Cannot create multiple instances of Singleton Type"
		instance = Self
	EndMethod

	Function Create:TSingleton()
		Return TSingleton.GetInstance()
	End Function
	
	Function GetInstance:TSingleton()
		If Not instance
			Return New TSingleton
		Else
			Return instance
		EndIf
	EndFunction
'#End Region 
	
EndType

Notice the instance = self in the new method. I'll update this on the next BLIde version.


Muttley(Posted 2008) [#7]
@ziggy: Doh!

I've just checked through my current code-base and that line is correctly there in every single Singleton Type I'm using. Dunno how it managed to slip out of the example I posted on the BLIde forum, but that's what I Ctrl-C, Ctrl-Ved here too.