Skip to content

Instantly share code, notes, and snippets.

@alapini
Forked from icambridge/interface.go
Created January 2, 2017 18:40
Show Gist options
  • Save alapini/764b365f4f07f510f9551c17ff261112 to your computer and use it in GitHub Desktop.
Save alapini/764b365f4f07f510f9551c17ff261112 to your computer and use it in GitHub Desktop.
Observer pattern - golang
type TestCallBack struct {
}
func (c *TestCallBack) Exec(o *Observable) {
log.Println(o.Name)
}
type Callback interface {
Exec(h *Observable)
}
package main
import (
"log"
)
type Observable struct {
Name string
}
type TestCallBack struct {
}
func (c *TestCallBack) Exec(o *Observable) {
log.Println(o.Name)
}
type Callback interface {
Exec(h *Observable)
}
type Observer struct {
callbacks []Callback
}
func (o *Observer) Add(c Callback) {
o.callbacks = append(o.callbacks, c)
}
func (o *Observer) Process(oe *Observable) {
for _, c := range o.callbacks {
c.Exec(oe)
}
}
func main() {
oe := Observable{Name: "Hello World"}
o := Observer{}
o.Add(&TestCallBack{})
o.Process(&oe)
}
type Observer struct {
callbacks []Callback
}
func (o *Observer) Add(c Callback) {
o.callbacks = append(o.callbacks, c)
}
func (o *Observer) Process(oe *Observable) {
for _, c := range o.callbacks {
c.Exec(oe)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment