定义了对象之间的一对多依赖,当一个对象改变状态时它所有的依赖者都会收到通知并自动更新。
package main
import "fmt"
type Subject struct{
observers []*Observer
temp float32
humidity float32
pressure float32
}
type Observer struct{
subject *Subject
temp float32
humidity float32
pressure float32
}
//注册,删除,通知
func (s *Subject) RegisterObserver(o *Observer){
s.observers = append(s.observers, o)
}
func (s *Subject) RemoveObserver(o Observer){
size := len(s.observers)
if size>0 {
s.observers = s.observers[:size-1]
}
}
func (s Subject) NotifyObservers(){
for _,o := range s.observers {
o.update(s.temp, s.humidity, s.pressure)
}
}
//主题改变
func (s *Subject) ChangeMeasure(temp float32, humidity float32, pressure float32){
s.temp = temp
s.humidity = humidity
s.pressure = pressure
s.NotifyObservers()
}
//拉
func (s Subject) getTemperature() float32{
return s.temp
}
func (s Subject) getHumidity() float32{
return s.humidity
}
func (s Subject) getPressure() float32{
return s.pressure
}
//观察者按主题更新,推
func (o *Observer) update(temp float32, humidity float32, pressure float32){
o.temp = temp
o.humidity = humidity
o.pressure = pressure
fmt.Println("display value:", o.temp, o.humidity, o.pressure)
}
//观察者按主题更新,拉
func (o *Observer) updatePull(s *Subject){
o.temp = s.getTemperature()
o.humidity = s.getHumidity()
o.pressure = s.getPressure()
fmt.Println("display value:", o.temp, o.humidity, o.pressure)
}
//新建一个观察者
func NewObserver(s *Subject) *Observer{
o := &Observer{subject:s}
s.RegisterObserver(o)
return o
}
func main () {
s := &Subject{}
o1 := NewObserver(s)
o2 := NewObserver(s)
s.ChangeMeasure(12,3,4)
fmt.Println(s,o1,o2)
s.ChangeMeasure(1,6.3,4)
o1.updatePull(s)
}