亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Go 方式實現觀察者設計模式

Go 方式實現觀察者設計模式

Go
蠱毒傳說 2023-07-04 15:04:17
我的經驗是使用 OOP 語言,但我已經開始嘗試 Go。我無法找到在 Go 中實現觀察者設計模式的最佳方法。我按如下方式組織我的項目,其中observers文件夾中的所有內容都是 的一部分package observers,并且subjects文件夾中的所有內容都是package subjects.?將觀察者附加到主題是在 中完成的main.go。my-project/? main.go? observers/? ? observer.go? ? observer_one.go? ? observer_two.go? subjects/? ? subject.go? ? subject_one.go我在 Go wiki 中看到過有關接口的部分:Go 接口通常屬于使用接口類型值的包,而不是實現這些值的包。實現包應該返回具體的(通常是指針或結構)類型:這樣,可以將新方法添加到實現中,而不需要大量重構。牢記 Go Wiki 的評論。我已經這樣實現了(省略了函數實現):主題.go:type ObserverInterface interface {? ? Update(subject *Subject, updateType string)}type Subject struct {? ? observers map[string][]ObserverInterface}func (s *Subject) Attach(observer ObserverInterface, updateType string) {}func (s *Subject) Detach(observer ObserverInterface, updateType string) {}func (s *Subject) notify(updateType string) {}觀察者.go:type SubjectInterface interface {? ?Attach(observer Observer, updateType string)? ?Detach(observer Observer, updateType string)? ?notify(updateType string)}type Observer struct {? ? uuid uuid.UUID}觀察者_one.gotype ObserverOne struct {? ? Observer}func (o *ObserverOne) Update(subject *SubjectInterface, updateType string) {}主程序subjectOne := &SubjectOne{}observerOne := &ObserverOne{Observer{uuid: uuid.New()}}subjectOne.Attach(observerOne, "update_type")我希望能夠使用in 方法SubjectInterface的參數,這樣我就可以避免我的包和我的包之間存在依賴關系,但我收到以下編譯時錯誤。Update()ObserverOnesubjectobserverobservers/observer_one.go:29:35: cannot use &observer (type *ObserverOne) as type subjects.ObserverInterface in argument to SubjectOne.Subject.Attach:? ? *ObserverOne does not implement subjects.ObserverInterface (wrong type for Update method)? ? ? ? have Update(*SubjectInterface, string)? ? ? ? want Update(*subjects.Subject, string)Update()如果我用以下內容替換observer_one.go中的定義,它可以正常編譯,但我認為這個想法是使用接口來解耦包:func (o *ObserverOne) Update(subject *subjects.Subject, updateType string) {}
查看完整描述

1 回答

?
白衣染霜花

TA貢獻1796條經驗 獲得超10個贊

首先,不要使用接口指針。

func (o *ObserverOne) Update(subject *SubjectInterface, updateType string) {}

應該

func (o *ObserverOne) Update(subject SubjectInterface, updateType string) {}

其次,您已將接口定義為需要具體類型:

type ObserverInterface interface {
    Update(subject *Subject, updateType string)
}

相反,讓它接受一個接口:

type ObserverInterface interface {
    Update(subject SubjectInterface, updateType string)
}


查看完整回答
反對 回復 2023-07-04
  • 1 回答
  • 0 關注
  • 167 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號