【发布时间】:2021-09-12 14:56:34
【问题描述】:
在下面的代码中,我有一个较低级别的模块RelationshipBrowser 定义了一个FindAllChildrenOf 方法,我有一个结构Relationships,它的属性relations 是一个切片和另一个名为Research 的结构作为财产browser。我为Relationships声明了一个接收器函数FindAllChildrenOf,为Research声明了另一个接收器函数Investigate,我想我的问题是,当我在函数Investigate中实现逻辑时,它显然是在调用浏览器界面来触发函数FindAllChildrenOf 并自动知道我指的是类型Relationship。我的困惑是,RelationshipBrowser 和Relationships 在这种情况下如何连接,而它们似乎没有连接?
const (
Parent Relationship = iota
Child
Sibiling
)
type Person struct {
name string
}
type Info struct{
from *Person
relatiionship Relationship
to *Person
}
// low-level module
type RelationshipBrowser interface{
FindAllChildrenOf(name string)[]*Person
}
type Relationships struct{
relations []Info
}
func (r *Relationships)AddParentAndChild(parent,child *Person){
r.relations = append(r.relations, Info{parent,Parent,child})
r.relations = append(r.relations, Info{child,Child,parent})
}
func (r *Relationships)FindAllChildrenOf(name string)[]*Person{
result:= make([]*Person,0)
for i,v:= range r.relations{
if v.relatiionship == Parent && v.from.name==name{
result = append(result, r.relations[i].to)
}
}
return result
}
// high-level module
type Research struct{
// break DIP
// relationships Relationships
browser RelationshipBrowser
}
func (r *Research)Investigate(){
// relations:= r.relationships.relations
// for _, rel := range relations{
// if rel.from.name == "John" && rel.relatiionship == Parent{
// fmt.Println("John has a child called", rel.to.name)
// }
// }
children:=r.browser.FindAllChildrenOf("John")
for _,child:=range children{
fmt.Println("John has a child called", child.name)
}
}
func main(){
parent:= Person{"John"}
child1:= Person{"Chris"}
child2:= Person{"Matt"}
relationships:= Relationships{}
relationships.AddParentAndChild(&parent,&child1)
relationships.AddParentAndChild(&parent,&child2)
r := Research{&relationships}
r.Investigate()
}
【问题讨论】:
-
golang 中的接口是隐式的。 tour.golang.org/methods/10