package main
import (
"fmt"
"runtime"
"time"
)
type Dispatcher struct {
ID int
callbacks []func()
}
func (d *Dispatcher) Subscribe(cb func()) {
d.callbacks = append(d.callbacks, cb)
}
func (d *Dispatcher) Dispatch() {
for _, cb := range d.callbacks {
cb()
}
}
func (d *Dispatcher) callback() {
fmt.Printf("Dispatcher:%d callback\n", d.ID)
}
func callback() {
fmt.Printf("Stand alone callback\n")
}
func main() {
// List of dispatchers
var disps []*Dispatcher
// Creates some dispatchers
for i := 1; i <= 5; i++ {
d := &Dispatcher{ID: i}
runtime.SetFinalizer(d, func(d *Dispatcher) {
fmt.Printf("Dispatcher:%d finalizer\n", d.ID)
})
// Subscribe to external function
d.Subscribe(callback)
// Subscribe to internal method.
// It will prevent finalizer to run (??)
//d.Subscribe(d.callback)
disps = append(disps, d)
}
// Test dispatch
for _, d := range disps {
d.Dispatch()
}
// Remove references to all dispatchers and force GC
// Finalizers should be executed.
disps = nil
runtime.GC()
// Give some time
time.Sleep(2)
}