Go 实现常用设计模式(五)观察者模式

观察者模式 (observer)

意图:
定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
关键代码:
被观察者持有了集合存放观察者(收通知的为观察者)
应用实例:

  1. 报纸订阅,报社为被观察者,订阅的人为观察者
  2. MVC模式,当model改变时,View视图会自动改变,model为被观察者,View为观察者

Go实现观察者模式

package observer

import "fmt"

// 报社 —— 客户
type Customer interface {
    update()
}

type CustomerA struct {
}

func (*CustomerA) update() {
    fmt.Println("我是客户A, 我收到报纸了")
}

type CustomerB struct {
}

func (*CustomerB) update() {
    fmt.Println("我是客户B, 我收到报纸了")
}

// 报社 (被观察者)
type NewsOffice struct {
    customers []Customer
}

func (n *NewsOffice) addCustomer(customer Customer) {
    n.customers = append(n.customers, customer)
}

func (n *NewsOffice) newspaperCome() {
    // 通知所有客户
    n.notifyAllCustomer()
}

func (n *NewsOffice) notifyAllCustomer() {
    for _, customer := range n.customers {
        customer.update()
    }
}

测试用例

package observer

import "testing"

func TestObserver(t *testing.T) {

    customerA := &CustomerA{}
    customerB := &CustomerB{}

    office := &NewsOffice{}
    // 模拟客户订阅
    office.addCustomer(customerA)
    office.addCustomer(customerB)
    // 新的报纸
    office.newspaperCome()

}

具体代码

更详细的代码可参考:https://github.com/pibigstar/go-demo 里面包含了 Go 常用的设计模式、Go 面试易错点、简单的小项目(区块链,爬虫等)、还有各种第三方的对接(redis、sms、nsq、elsticsearch、alipay、oss...),如果对你有所帮助,请给个 Star,你的支持,是我最大的动力!

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!