观察者模式,核心在于
- 被观察者的信息发生改变会通知观者者
- 被观察者可以添加和删除观察者
- 观察者需要有更新的行为
python实现
# 观察者
class Observer:def __init__(self, name):self.name = namedef update(self, content):print(f"【{self.name}】接收到消息:【{content}】")# 被观察者
class Subject:def __init__(self):self.observers = []self.msg = ""def attach(self, observer: Observer):self.observers.append(observer)def detach(self, observer: Observer):self.observers.remove(observer)def notify(self, content: str):self.msg = contentfor observer in self.observers:observer.update(self.msg)if __name__ == '__main__':# 创建被观察者s = Subject()# 观察者o1 = Observer(name="小明")o2 = Observer(name="小红")s.attach(o1)s.attach(o2)s.notify("更新消息了")
go 实现
package mainimport ("fmt"
)// 观察者
type Observer struct {name string
}func NewObserver(name string) Observer {return Observer{name: name}
}
func (o *Observer) Update(content string) {content = fmt.Sprintf("【%s】接受到消息:【%s】\n", o.name, content)fmt.Println(content)
}// 被观察者
type Subject struct {Observers []*Observermsg string
}func NewSubject() Subject {return Subject{}
}// 添加观察者
func (s *Subject) attach(observer *Observer) {s.Observers = append(s.Observers, observer)
}// 删除观察者
func (s *Subject) detach(observer *Observer) {var newObservers []*Observerfor _, o := range s.Observers {if o != observer {newObservers = append(newObservers, o)}}s.Observers = newObservers
}// 被观察者通知消息
func (s *Subject) notify(msg string) {s.msg = msgfor _, observer := range s.Observers {observer.Update(s.msg)}
}
func main() {// 创建被观察者s := NewSubject()// 创建观察者o1 := NewObserver("小明")o2 := NewObserver("小红")// 添加观察者s.attach(&o1)s.attach(&o2)s.notify("更新消息了")s.detach(&o1)s.notify("有更新消息了")
}