I have a singleton(-ish) type.
What is the difference between using fields and globals within the type?
What is the difference between using fields and globals within the type?
Type TSingleton Global singleton:TSingleton Field value:Int Function Create:TSingleton() If singleton = Null Then singleton = New TSingleton Return singleton End Function End Type Local a:TSingleton = TSingleton.Create() a.value = 100 Local b:TSingleton = TSingleton.Create() Print b.value
'Example Singleton. This is one of two ways, and you can use a Field just as I have used a Global, 'but you would need To keep a reference of what was created. 'The advantage of using the Global is that the code can simply be Tsingleton.GetInstance() 'instead of having a global instance elsewhere in the code, it is kept tidily in the Type interface. Type Tsingleton Global Instance:Tsingleton 'Summary: Constructor- Create the Tsingleton singleton. Function Create:Tsingleton() 'You could also overload the New function... If instance=Null Then instance=New Tsingleton Else RuntimeError "TSingleton is a Singleton. You may only create one instance!" EndIf End Function Function GetSingleton:Tsingleton() Return Instance End Function End Type 'Example use of Global in a none Singleton: Type Tplayer Global PlayerList:TList Field Name:String 'Summary: Constructor- Create a player Function Create:Tplayer(name:String) 'You could also overload the New function... Local player:Tplayer=New Tplayer If Playerlist=Null Then playerlist=New TList playerlist.addlast(Player) player.name=name Return Player End Function 'Summary: Retrieve a list of players. Function GetPlayerList:TList() Return Playerlist End Function 'Destructor Method Delete() Playerlist.remove(Self) End Method 'Summary: Get this current players name. Method Getname:String() Return Self.Name End Method End Type 'Correct use of Singleton with this code: 'Create the Tsingleton instance. Tsingleton.Create() 'Call a second time? (should error and tell the coder he's cocked up! 'Tsingleton.Create() 'Correct use of Tplayer: Global Player1:Tplayer Global Player2:Tplayer Player1=Tplayer.Create("Damien") Player2=Tplayer.Create("Tracy") 'Code that doesn't know what players have been created: Local Playerlist:TList=Tplayer.GetPlayerList() For Local Player:Tplayer=EachIn Playerlist Print "Look! I can see "+player.getname()+"!" Next
Type TSingleton ... End Type Global FMySingleton: TSingleton Function MySingleton: TSingleton If FMySingleton = Null Then FMySingleton = New TSingleton End If Return FMySingleton End Function 'Somewhere in your code MySingleton.SomeValue = 1 MySingleton.DoSomething()
local a:TSingleton = TSingleton.Create(); Local b:TSingleton = a.getInstance();