码迷,mamicode.com
首页 > 其他好文 > 详细

观察者模式

时间:2015-04-17 01:01:15      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

    观察者模式:在对象之间定义一对多的依赖,这样一来,当一个对象改变状态,依赖它的对象都会收到通知,并自动更新。——《HEAD FIRST 设计模式》

    我的golang代码:

package observer

import (
    "container/list"
    "fmt"
)

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

type Observer interface {
    Update()
}

type DisplayElement interface {
    Display()
}

/////////////////////////////////////

type WeatherData struct {
    o *list.List
    t int // temperature
    h int // humidity
    p int // pressure
}

func NewWeatherData() *WeatherData {
    r := new(WeatherData)
    r.o = new(list.List)
    return r
}

func (o *WeatherData) RegisterObserver(ob Observer) {
    o.o.PushBack(ob)
}

func (o *WeatherData) RemoveObserver(ob Observer) {
    for e := o.o.Front(); e != nil; e = e.Next() {
        if e.Value == ob {
            o.o.Remove(e)
            return
        }
    }
}

func (o *WeatherData) NotifyObserver() {
    for e := o.o.Front(); e != nil; e = e.Next() {
        e.Value.(Observer).Update()
    }
}

//////////////////////////////////////

type CurrentConditionsDisplay struct {
}

func (o *CurrentConditionsDisplay) Update() {
    o.Display()
}

func (o *CurrentConditionsDisplay) Display() {
    fmt.Println("CurrentConditionsDisplay update!")
}

type StatisticsDisplay struct {
}

func (o *StatisticsDisplay) Update() {
    o.Display()
}

func (o *StatisticsDisplay) Display() {
    fmt.Println("StatisticsDisplay update!")
}

type ForecastDisplay struct {
}

func (o *ForecastDisplay) Update() {
    o.Display()
}

func (o *ForecastDisplay) Display() {
    fmt.Println("ForecastDisplay update!")
}

type ThirdPartyDisplay struct {
}

func (o *ThirdPartyDisplay) Update() {
    o.Display()
}

func (o *ThirdPartyDisplay) Display() {
    fmt.Println("ThirdPartyDisplay update!")
}
    个人感悟:待留。

观察者模式

标签:

原文地址:http://www.cnblogs.com/foolbread/p/4433639.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!