【问题标题】:How does lower level module and higher level module communicate in golanggolang中低级模块和高级模块如何通信
【发布时间】: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()

}

【问题讨论】:

标签: oop go


【解决方案1】:

go 自动知道我指的是关系类型。

是的,因为 Go 知道 RelationshipBrowser 的确切地址,所以它可以知道任何事情。 你也可以什么都知道,通过反射,见https://go.dev/blog/laws-of-reflection

在您的代码中,您在此处明确传递地址:

r := Research{&relationships}

RelationshipBrowser 和Relationships 通过这个地址连接在一起,因为Research 认为它是一个RelationshipBrowser,但它实际上是一个Relationships。

【讨论】:

    【解决方案2】:

    我刚刚发现通过调用r.Investigate,程序知道我指的是Relationship 结构。我仍然是围棋初学者,所以学习曲线很深。

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2013-05-09
    • 2020-03-14
    • 2017-09-22
    • 2011-04-16
    • 2023-03-29
    • 2011-06-10
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多