【发布时间】:2019-07-14 11:47:37
【问题描述】:
我的经验是使用 OOP 语言,但我已经开始尝试 Go。我无法找出在 Go 中实现 Observer design pattern 的最佳方法。
我按如下方式组织了我的项目,其中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
我看过this section in the Go wiki关于接口:
Go 接口通常属于使用接口类型值的包,而不是实现这些值的包。实现包应该返回具体(通常是指针或结构)类型:这样,新方法可以添加到实现中,而无需大量重构。
牢记来自 Go Wiki 的评论。我已经这样实现了(省略了函数实现):
subject.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) {}
observer.go:
type SubjectInterface interface {
Attach(observer Observer, updateType string)
Detach(observer Observer, updateType string)
notify(updateType string)
}
type Observer struct {
uuid uuid.UUID
}
observer_one.go
type ObserverOne struct {
Observer
}
func (o *ObserverOne) Update(subject *SubjectInterface, updateType string) {}
main.go
subjectOne := &SubjectOne{}
observerOne := &ObserverOne{Observer{uuid: uuid.New()}}
subjectOne.Attach(observerOne, "update_type")
我希望能够使用SubjectInterface 作为ObserverOne 中Update() 方法的参数,这样我就可以避免subject 包和observer 包之间存在依赖关系,但我得到以下信息编译时错误。
observers/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)
如果我将observer_one.go 中Update() 的定义替换为以下内容,它编译得很好,但我认为这个想法是使用接口解耦包:
func (o *ObserverOne) Update(subject *subjects.Subject, updateType string) {}
【问题讨论】:
标签: go design-patterns observer-pattern