Skip to content

Instantly share code, notes, and snippets.

@icambridge
Last active November 1, 2017 00:59
Show Gist options
  • Save icambridge/9708081 to your computer and use it in GitHub Desktop.
Save icambridge/9708081 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)
}
}
@gengen1988
Copy link

Hi icambridge. I believe this code is more like delegation pattern

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment