Delegation syntax
Delegation requires the Gosu keyword delegate within your class variable
definitions. Declaring a delegate is like declaring a special type of class variable.
The delegate
keyword has the following syntax:
delegate PRIVATE_VARIABLE_NAME represents INTERFACE_LISTOptionally, you can use the following syntax that specifies the type:
delegate PRIVATE_VARIABLE_NAME : TYPE represents INTERFACE_LISTThe INTERFACE_LIST is a list of one or more interface names, with commas separating multiple interfaces.
For example:
delegate _clipboardPart represents IClipboardPartIn the class constructor, create an instance of an object that implements the interface. For example:
construct() {
_clipboardPart = new ClipboardPart( this )
}
After the constructor runs, Gosu intercepts any method invocations on the object for that interface and forwards the method invocation to the delegated object.
Example
Let us look at complete code for this example.
The interface:
package test
interface IClipboardPart {
function canCopy() : boolean
function copy() : void
function canPaste() : boolean
function paste() : void
}
The delegate implementation class:
package test
class ClipboardPart implements IClipboardPart {
var _myOwner : Object
construct(owner : Object) {
_myOwner = owner
}
// This is an implementation of these methods...
override function canCopy() : boolean { return true }
override function copy() : void { print("Copied!")}
override function canPaste() : boolean { return true }
override function paste() : void { print("Pasted!") }
}
The class that delegates the IClipboardPart implementation
to another class:
package test
class MyWindow implements IClipboardPart {
delegate _clipboardPart represents IClipboardPart
construct() {
_clipboardPart = new ClipboardPart( this )
}
}
Finally, enter the following code into the Gosu Scratchpad:
uses test.MyWindow
var a = new MyWindow()
// Call a method handled on the delegate
a.paste()
This code prints:
Pasted!