:::tips 观察者模式又叫 发布订阅模式
:::
定义
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. 在对象之间定义一个一对多的依赖,当一个对象状态改变的时候,所有依赖的对象都会自动收到通知。
示例
同步阻塞方式
golang
package xtcp
import (
"container/list"
"log"
"testing"
)
func Test_Server(t *testing.T) {
subject := ConcreteSubject{}
one := ConcreteObserveOne{}
two := ConcreteObserveTwo{}
subject.RegisterObserver(&one)
subject.RegisterObserver(&two)
subject.NotifyObserver("test")
subject.RemoveObserver(&one)
subject.NotifyObserver("test - 2")
}
type Subject interface {
RegisterObserver(observer Observer)
RemoveObserver(observer Observer)
NotifyObserver(message string)
}
type Observer interface {
Update(message string)
}
type ConcreteSubject struct {
observers list.List
}
func (c *ConcreteSubject) RegisterObserver(observer Observer) {
c.observers.PushBack(observer)
}
func (c *ConcreteSubject) RemoveObserver(observer Observer) {
for e:= c.observers.Front(); e!= nil; e = e.Next(){
if e.Value == observer{
c.observers.Remove(e)
return
}
}
}
func (c *ConcreteSubject) NotifyObserver(message string) {
for e:= c.observers.Front(); e!= nil; e = e.Next(){
observer := e.Value.(Observer)
observer.Update(message)
}
}
type ConcreteObserveOne struct {
}
type ConcreteObserveTwo struct {
}
func (o *ConcreteObserveOne) Update(message string) {
log.Println("one" + message)
}
func (o *ConcreteObserveTwo) Update(message string) {
log.Println("two" + message)
}
异步队列方式
:::tips 没错, 消息队列就是一种, 并且耦合更小, 因为 被观察者感知不到观察者的存在
缺点是需要引入 消息队列 中间件
:::