Golang — Observer Pattern vs Channels
Introduction
The Observer Pattern is a popular design pattern that allows an object (known as the subject) to notify its dependent objects (known as observers) automatically when a change occurs in the subject. In Golang, there are two main ways to implement the Observer Pattern: using interfaces and using channels. In this article, we’ll compare the classic Observer Pattern with Golang channels, and discuss the benefits and drawbacks of each approach.
Classic Observer Pattern
In the classic Observer Pattern, the subject maintains a list of observers, and provides methods to register and remove observers from the list. When a change occurs in the subject, it calls the update()
method on all registered observers, passing in the updated data as a parameter.
Here’s an example implementation of the classic Observer Pattern in Golang using interfaces:
type subject interface {
registerObserver(observer)
removeObserver(observer)
notifyObservers()
}
type observer interface {
update()
}
type weatherStation struct {
temperature float64
observers []observer
}
type temperatureDisplay struct{}
func (w *weatherStation) registerObserver(o observer) {
w.observers = append(w.observers, o)
}
func (w *weatherStation) removeObserver(o observer) {
for i, observer := range w.observers {
if observer == o {
w.observers = append(w.observers[:i], w.observers[i+1:]...)
break…