Skip to content

Instantly share code, notes, and snippets.

@sandeepone
Forked from icambridge/interface.go
Created October 13, 2017 19:38
Show Gist options
  • Save sandeepone/073c962c16bba687ca11ca48d3cf7ae0 to your computer and use it in GitHub Desktop.
Save sandeepone/073c962c16bba687ca11ca48d3cf7ae0 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