Observer

In many situations, there is one entity (subject) with state and several others (observers) that are interested in that state. The observer pattern is a software design pattern that defines the interaction between the subject and the observer. Essentially, the subject maintains a list of observers and notifies them of any state changes. The pattern is shown in this figure:

Here is the implementation in Go:

// The Subject

type Subject struct {
observers []Observer
state string
}

func (s *Subject) Attach(observer Observer) {
s.observers = append(s.observers, observer)
}


func (s *Subject) SetState(newState string) {
s.state = newState
for _,o:= range(s.observers) {
o.Update()
}
}

func (s *Subject) GetState() string {
return s.state
}

// The Observer Inteface

type Observer interface {
Update()
}

// Concrete Observer A

type ConcreteObserverA struct {
model *Subject
viewState string
}

func (ca *ConcreteObserverA) Update() {
ca.viewState = ca.model.GetState()
fmt.Println("ConcreteObserverA: updated view state to ", ca.viewState)
}

func (ca *ConcreteObserverA) SetModel(s *Subject) {
ca.model = s
}

And the client will call as follows:

func client() {
// create Subject
s:= Subject{}

// create concrete observer
ca:= &ConcreteObserverA{}
ca.SetModel(&s) // set Model

// Attach the observer
s.Attach(ca)

s.SetState("s1")
}
Note that in the textbook form of the object pattern (shown in the figure), the model reference is in the observer interface (as in, an abstract base class in Java). However, since in Go interfaces can't have data and there is no inheritance, the model reference gets pushed down to the concrete observers.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset