Duplicate Singletons
BlitzMax Forums/BlitzMax Programming/Duplicate Singletons 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
Ah! Thanks - I was under the impression you couldn't override New(). Reviewing it, I was just recalling that it can't accept parameters.
@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:
Notice the instance = self in the new method. I'll update this on the next BLIde version.
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.
@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.
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.