使用Go语言实现观察者模式

2023-08-10 19:29:30 浏览数 (1)

观察者模式是一种行为设计模式,当对象的状态改变时,它允许某些对象通知其他对象。这通常被用于实现事件处理系统。下面我们通过一个简单的天气监控系统来演示在Go语言中如何实现观察者模式。

首先,我们定义Observer(观察者)和Subject(主题)接口:

代码语言:javascript复制
type Observer interface {
    Update(temperature float64, humidity float64, pressure float64)
}

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

然后,我们创建一个实现了Subject接口的WeatherData结构:

代码语言:javascript复制
type WeatherData struct {
    observers   []Observer
    temperature float64
    humidity    float64
    pressure    float64
}

func NewWeatherData() *WeatherData {
    return &WeatherData{}
}

func (w *WeatherData) RegisterObserver(o Observer) {
    w.observers = append(w.observers, o)
}

func (w *WeatherData) RemoveObserver(o Observer) {
    for i, observer := range w.observers {
        if observer == o {
            w.observers = append(w.observers[:i], w.observers[i 1:]...)
        }
    }
}

func (w *WeatherData) NotifyObservers() {
    for _, observer := range w.observers {
        observer.Update(w.temperature, w.humidity, w.pressure)
    }
}

func (w *WeatherData) measurementsChanged() {
    w.NotifyObservers()
}

func (w *WeatherData) SetMeasurements(temperature float64, humidity float64, pressure float64) {
    w.temperature = temperature
    w.humidity = humidity
    w.pressure = pressure
    w.measurementsChanged()
}

接下来,我们创建一个实现了Observer接口的CurrentConditionsDisplay结构:

代码语言:javascript复制
type CurrentConditionsDisplay struct {
    temperature float64
    humidity    float64
    weatherData Subject
}

func NewCurrentConditionsDisplay(weatherData Subject) *CurrentConditionsDisplay {
    c := &CurrentConditionsDisplay{weatherData: weatherData}
    weatherData.RegisterObserver(c)
    return c
}

func (c *CurrentConditionsDisplay) Update(temperature float64, humidity float64, pressure float64) {
    c.temperature = temperature
    c.humidity = humidity
    c.Display()
}

func (c *CurrentConditionsDisplay) Display() {
    fmt.Printf("Current conditions: %.2f F degrees and %.2f humidityn", c.temperature, c.humidity)
}

最后,我们的客户端代码看起来像这样:

代码语言:javascript复制
func main() {
    weatherData := NewWeatherData()

    NewCurrentConditionsDisplay(weatherData)

    weatherData.SetMeasurements(80, 65, 30.4)
    weatherData.SetMeasurements(82, 70, 29.2)
    weatherData.SetMeasurements(78, 90, 29.2)
}

运行这段代码,你会看到随着WeatherData的数据更新,CurrentConditionsDisplay的显示也相应的更新了。这就是观察者模式的应用,希望你能从中找到它的价值。

0 人点赞