Thursday, February 8, 2018

Observer Pattern in Golang

Observer pattern is one of my favorite pattern in programming.
Observer pattern is used when there is one-to-many relationship between objects such as if one object is modified, its dependent objects are to be notified automatically. Observer pattern falls under behavioral pattern category.

Here is my implementation in Golang shown as below:

 Observer with file interface.go
type ObserverCallBack struct {
}
func (c *ObserverCallBack) Exec(o *Observable) {
    log.Println(o.Name)
}
type Callback interface {
    Exec(h *Observable)
}




Observer Notifier with file observer.go
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)
    }
}



Full Code with main.go
package main
import (
       "log"
)
type Observable struct {
    Name string
}
type ObserverCallBack struct {
}
func (c *ObserverCallBack) 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(&ObserverCallBack{})
    o.Process(&oe)
}
  

Result shown as below










Other Topics:

No comments:

Post a Comment