Singleton type question
BlitzMax Forums/BlitzMax Beginners Area/Singleton type question
| ||
Hello, I understand a Singleton class/type is a global and common one, right? If yes I would like to ask you if this is a good practice: [TSingleton] Type TSingleton '#Region Constructors Global instance:TSingleton Method New() If instance Throw "Cannot create multiple instances of Singleton Type" EndMethod Function Create:TSingleton() Return Self.GetInstance() End Function Function GetInstance:TSingleton() If Not instance instance = New TSingleton Return instance Else Return instance EndIf EndFunction Global theValue:Int EndType [TSecond] Import "tsingleton.bmx" Type TSecond Method modTheX(tmpValue:Int) TSingleton.theValue = tmpValue End Method End Type [TMain] Import "tsingleton.bmx" Import "tsecond.bmx" Global myTs:TSingleton Global mySecond:TSecond myTs = New TSingleton myTs.Create() myTs.theValue = 10 mySecond = New TSecond mySecond.modTheX(200) Print myTs.theValue TSingleton.theValue = 122 Print myTs.theValue I mean I want to have some kind of Global class/type and access the values from it, from my other classes.. also, is there a tutorial or document which explain the singleton use? Last edited 2012 |
| ||
Function Create:TSingleton() Return Self.GetInstance() End Function Self is only possible in instances -> methods. So you should use "TSingleTon.GetInstance()" there. As you declared "instance" as a global, you can use it within the classes functions as "instance" instead of "TSingleTon.instance" (you already did that). Function GetInstance:TSingleton() If Not instance instance = New TSingleton Return instance Else Return instance EndIf EndFunction You make your life harder than needed Function GetInstance:TSingleton() If Not instance then instance = New TSingleton Return instance EndFunction If you return "instance" in all cases, no need to write it multiple times. Other classes can change "theValue" directly as it is accessible (TSingleTon.theValue). There is still no need to use "Method modTheX" as it doesn't use instance-specific values. So you could also use a function instead of a method. So you are able to avoid "mySecond = New TSecond" as you then achieve the same with "TSecond.modTheX(200)". bye Ron |