观察者模式(Observer Design Pattern)

观察者模式,又称发布订阅模式,比如对象存在一对多关系,当其中某个对象被修改时会自动通知依赖的其它对象。

代码示例

package observer

import "fmt"

type Observer interface {
    OnChange(Subject)
    Subscribe(*Subject)
}

type Subject struct {
    observers []Observer
    state     int
}

func (sub *Subject) Publish(state int) {
    sub.state = state
    sub.notifyAllObservers()
}
func (sub *Subject) Attach(o Observer) {
    sub.observers = append(sub.observers, o)
}
func (sub Subject) notifyAllObservers() {
    fmt.Println("notify all")
    for _, observer := range sub.observers {
        observer.OnChange(sub)
    }
}

type AObserver struct {
}

func (o AObserver) OnChange(sub Subject) {
    fmt.Println("AObserver receive:", sub.state)
}
func (o AObserver) Subscribe(s *Subject) {
    s.Attach(o)
}

type BObserver struct {
}

func (o BObserver) OnChange(sub Subject) {
    fmt.Println("BObserver receive:", sub.state)
}

func (o BObserver) Subscribe(s *Subject) {
    s.Attach(o)
}

调用:

subject := &Subject{}
(&AObserver{}).Subscribe(subject)
(&BObserver{}).Subscribe(subject)

subject.Publish(1)
// Output:
// notify all
// AObserver receive: 1
// BObserver receive: 1

results matching ""

    No results matching ""