gpt4 book ai didi

go - 同一方法的多个实现可能与 Go 和接口(interface)有不同的依赖关系

转载 作者:行者123 更新时间:2023-12-01 21:18:10 25 4
gpt4 key购买 nike

我有一个关于使用接口(interface)的问题。

我有一个 Compute(a, b int) 方法,它有 2 个实现,具体取决于接收器。

func (addition *Addition) Compute(a, b int) int{
return a+b
}

func (mult *Multiplication) Compute(a, b int) int{
return a*b
}


type myInterface{
Compute(a, b int) int
}

假设我需要在乘法中调用 webService 来获取 a 的值。

现在我们有:
func (mult *Multiplication) Compute(iface WSInterface, a, b int) int{
a := iface.getA()
return a*b
}

现在,我需要添加 iface WSInterface进入 Compute()接口(interface)定义,并将其添加到 Addition,即使它不需要它。

我将结束:
type Addition struct{}

type Multiplication struct{}


func main() {
addition := &Addition{}
multiplication := &Multiplication{}
res1 := addition.Compute(nil, 1, 2)
res2 := addition.Compute(multiplication, 3, 4)
fmt.Print(res1, res2)
}

type WSInterface interface {
getA() int
}

func (mult *Multiplication) getA() int {
return 1 // Mocked
}

type myInterface interface {
Compute(iface myInterface, a, b int) int
}

func (addition *Addition) Compute(iface WSInterface, a, b int) int {
return a + b
}

func (mult *Multiplication) Compute(iface WSInterface, a, b int) int {
return iface.getA() * b
}

但除此之外,它不会被使用。

在现实生活中,您可以对不同的微服务有多个依赖项,我发现定义不会在函数中使用的参数并不是那么优雅。这里一定有问题。

这样做可以吗,这是一个不好的模式,或者我应该如何解决它?

最佳答案

这些特殊的接口(interface)/对象应该在构造函数中传递,保持接口(interface)本身干净。

就像是:

type Multiplication struct {
iface otherInferface
// .. other Multiplication-specific fields
}

func NewMultiplication(iface otherInterface) *Multiplication {
return &Multiplication{iface: iface}
}

进而:
func (mult *Multiplication) Compute(a, b int) int{
a := mult.iface.getA()
return a*b
}

所以你的 myInterface保持简单干净:
type myInterface interface {
Compute(a, b int)
}

关于go - 同一方法的多个实现可能与 Go 和接口(interface)有不同的依赖关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61229362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com