Observer Pattern in Golang

Prince Pereira
1 min readApr 23, 2020

Observer Pattern is achieved mainly using 2 objects:

Observable : The one who is being observed. He can perform 2 operations:

  • Adding observers to observer list [func (o *Observable) addObserver(obs Observer)]. The observers are maintained in a local list.
  • Notify all observers when any field value is changed [func (o *Observable) NotifyObservers(value string)]

Observer : One who keeps monitoring other’s activities. He will have a “Update(name string)” method which gets called once the Observable guy sends notification saying “Hey I have a change in my value”. [func (o *Observer) Update(value string)]

Here is how the code looks like:

File: observable.go
Code:

package maintype Observable struct{
Observers []Observer
}
func (o *Observable) addObserver(obs Observer){
o.Observers = append(o.Observers, obs)
}
func (o *Observable) NotifyAll(value string){
for _, ob := range o.Observers {
ob.Update(value)
}
}

File: observer.go
Code:

package mainimport "fmt"type Observer interface {
Update(value string)
}
func createCustomer(name string) *Customer{
return &Customer{Name:name}
}
type Customer struct {
Name string
}
func (c *Customer) Update(value string){
fmt.Printf(“Customer : %s , New value: %s\n”,c.Name, value)
}

File: main.go
Code:

package maintype Item struct{
Observable
Name string
}
func createItem(name string) *Item{
return &Item{Name:name}
}
func (i *Item) setName(name string){
i.Name = name
i.NotifyAll(name)
}
func main(){
i := createItem("Nike Shoes")
c1 := createCustomer("Raj")
c2 := createCustomer("Rohit")
i.addObserver(c1)
i.addObserver(c2)
i.setName("Adidas")
}

Output

$ go run main.go 
Customer : Raj , New value: Adidas
Customer : Rohit , New value: Adidas

--

--

Prince Pereira

Senior Software Engineer - Microsoft | SDN | Java | Golang | DS & Algo | Microservices | Kubernetes | Docker | gRPC & Protocol Buffer