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

火蜥蜴 · · 633 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

代码

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, humidity 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, humidity 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

有疑问加站长微信联系(非本文作者)

本文来自:Segmentfault

感谢作者:火蜥蜴

查看原文:Just for fun——go实现一下观察者模式

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

633 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传