设计模式
观察者模式
观察者模式,也被称为发布订阅模式(Publish-Subscribe Design Pattern)
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
翻译中文:
在对象之间定义一个一对多的依赖,当一个对象状态改变的时候,所有依赖的对象都会自动收到通知。
观察者模式的
应用场景
观察者模式需要三个条件:观察者 被观察,话题订阅
实际场景可以是:
- 公众号推送消息,独立的微信号关注多个公众号 ,每次总能收到公众号发布的更新内容,订阅号也会将公众号置顶标红提醒
- 邮件订阅
- RSS Feeds
代码
package observer import "fmt" type Subject struct { observers []Observer context string } func NewSubject() *Subject { return &Subject{ observers: make([]Observer, 0), } } func (s *Subject) Attach(o Observer) { s.observers = append(s.observers, o) } func (s *Subject) notify() { for _, o := range s.observers { o.Update(s) } } func (s *Subject) UpdateContext(context string) { s.context = context s.notify() } type Observer interface { Update(*Subject) } type Reader struct { name string } func NewReader(name string) *Reader { return &Reader{ name: name, } } func (r *Reader) Update(s *Subject) { fmt.Printf("%s receive %s\n", r.name, s.context) }
测试代码
package observer func ExampleObserver() { subject := NewSubject() reader1 := NewReader("reader1") reader2 := NewReader("reader2") reader3 := NewReader("reader3") subject.Attach(reader1) subject.Attach(reader2) subject.Attach(reader3) subject.UpdateContext("observer mode") // Output: // reader1 receive observer mode // reader2 receive observer mode // reader3 receive observer mode }