Just for fun——go实现一下观察者模式

代码

package main

import (
    "fmt"
)

type Subject interface {
    RegisterObserver(o Observer)
    RemoveObserver(o Observer)
    NotifyAllObservers()
}

type Observer interface {
    // 温度,湿度,气压
    Update(temp float32,humidity float32,pressure float32)
}

type WeatherData struct {
    Temperature float32
    Humidity    float32
    Pressure    float32
    Observers   map[Observer]bool
}

func NewWeathData() *WeatherData {
    return &WeatherData{
        Observers: make(map[Observer]bool),}
}

func (wd *WeatherData) RegisterObserver(o Observer) {
    wd.Observers[o] = true
}

func (wd *WeatherData) RemoveObserver(o Observer) {
    if _,ok := wd.Observers[o]; ok {
        delete(wd.Observers,o)
    }
}

func (wd *WeatherData) NotifyAllObservers() {
    for o,_ := range wd.Observers {
        o.Update(wd.Temperature,wd.Humidity,wd.Pressure)
    }
}

func (wd *WeatherData) SetMeasurements(temp float32,pressure float32) {
    wd.Temperature = temp
    wd.Humidity = humidity
    wd.Pressure = pressure
    wd.NotifyAllObservers()
}

type CurrentConditionsdisplay struct {
    Temperature float32
    Humidity    float32
    weathData   Subject
}

func NewCurrentConditionsdisplay(weathData Subject) *CurrentConditionsdisplay {
    ccd := &CurrentConditionsdisplay{
        weathData: weathData,}
    weathData.RegisterObserver(ccd)
    return ccd
}

func (ccd *CurrentConditionsdisplay) Update(temp float32,pressure float32) {
    ccd.Temperature = temp
    ccd.Humidity = humidity
    // pressure 没用到
    ccd.display()
}

func (ccd *CurrentConditionsdisplay) display() {
    fmt.Println("Current conditions: " + fmt.Sprintf("%v",ccd.Temperature) + "F degrees and " + fmt.Sprintf("%v",ccd.Humidity) + "% humidity")
}

func main() {
    weathData := NewWeathData()

    _ = NewCurrentConditionsdisplay(weathData)
    weathData.SetMeasurements(80,65,30.4)
    weathData.SetMeasurements(82,70,29.2)
    weathData.SetMeasurements(78,90,29.2)
}

测试

输出

Current conditions: 80F degrees and 65% humidity
Current conditions: 82F degrees and 70% humidity
Current conditions: 78F degrees and 90% humidity

相关文章

什么是Go的接口? 接口可以说是一种类型,可以粗略的理解为他...
1、Golang指针 在介绍Golang指针隐式间接引用前,先简单说下...
1、概述 1.1 Protocol buffers定义 Protocol buffe...
判断文件是否存在,需要用到"os"包中的两个函数: os.Stat(...
1、编译环境 OS :Loongnix-Server Linux release 8.3 CPU指...
1、概述 Golang是一种强类型语言,虽然在代码中经常看到i:=1...