Created
January 3, 2012 19:37
-
-
Save kellegous/1556515 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
// A simple event. | |
type Event int | |
// An interface for things that can send events. | |
type Dispatcher interface { | |
DispatchEvent(e Event) | |
ListenWith(f func(Dispatcher, Event)) | |
Equals(d Dispatcher) bool | |
} | |
// A thing that dispatches and can be composited. | |
type disp struct { | |
listener func(Dispatcher, Event) | |
} | |
func (d *disp) DispatchEvent(e Event) { | |
d.listener(d, e) | |
} | |
func (d *disp) ListenWith(f func(Dispatcher, Event)) { | |
d.listener = f | |
} | |
func (d *disp) Equals(o Dispatcher) bool { | |
switch t := o.(type) { | |
case *disp: | |
return t == d | |
} | |
return false | |
} | |
// A concrete thing that gives off events. | |
type Widget struct { | |
disp | |
Id int | |
} | |
func (w *Widget) fire() { | |
w.Id++ | |
w.DispatchEvent(Event(w.Id)) | |
} | |
// Where it all begins. | |
func main() { | |
a := Widget{} | |
b := Widget{} | |
// a listener func | |
listener := func(d Dispatcher, e Event) { | |
if a.Equals(d) { | |
fmt.Printf("Event: a(%d)\n", e) | |
return | |
} | |
if b.Equals(d) { | |
fmt.Printf("Event: b(%d)\n", e) | |
return | |
} | |
} | |
a.ListenWith(listener) | |
b.ListenWith(listener) | |
a.fire() | |
b.fire() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output is:
Event: a(1)
Event: b(1)