Interfaces
Monkey Forums/Monkey Programming/Interfaces| 
 | ||
| Looking over the Monkey docs, I see that it supports use of interfaces. I understand, basically, what they are. But what are some interesting and handy uses for them? | 
| 
 | ||
| when the extends system isnt flexible enough, I have only one interface in my game cos I wanted villages and people to take turns so i made an interface called 'turn_taker' I couldnt get village and person to extend turn_taker easily. village extended world_map_object and person extended iso_map_object so it would have been diffiuclt to make them both extend turn_taker. A tree is also a world_map_object and I didnt want a tree to take a turn Some programmers dont use extends at all and only use interfaces, this is silly because for example a GUI system would repeat a lot of code if it was programmed only with interfaces | 
| 
 | ||
| One example is callbacks: Say you want to want to know when some object has finished it's action. 
Interface EventHandler
	Method OnEvent:Void (id:String)
End
Class Action
	
	Field counter:Int
	Field listener:EventHandler
	Method Update:Void()
		counter += 1
		If counter > 99
			Stop()
		End
	End
	
	Method Stop:Void()
		If listener
			listener.OnEvent ("Counter Finished")
		End
	End
	
End
Class Game Implements EventHandler
	
	Field Actions:List<Action> = New List<Action>
	Method Update:Void()
		For Local a:Action = Eachin Actions
			a.Update()
		End
	End
	
	Method OnEvent:Void (id:String)
		Select id
			Case "Counter Finished"
				'Now do something
			Default
		End
	End
End
The game listens when an action has finished and when one does, the action notifies the game through the OnEvent Method. Example: Local game:Game = New Game Local action:Action = New action game.Actions.AddLast (action) action.listener = Game | 
| 
 | ||
| Is that the replacement for function pointers?  Are there no function pointers in Monkey? | 
| 
 | ||
| correct | 
| 
 | ||
|  @zoqfotpik: Is that the replacement for function pointers? Are there no function pointers in Monkey?  It's a way of (as Mark would put it) "kludging" function pointers, but that's not the sole purpose of interfaces. | 
| 
 | ||
| They are a limited form of multiple inheritance that is harder to go wrong with.  Like in slenkar's example. |