同一方法的多个实现,可能与Go和Interfaces具有不同的依赖性

问题描述 投票:0回答:1

我在使用接口时遇到问题。

我有一个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()接口定义中,并将其添加到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
}

但是,除此之外,不会使用。

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

可以这样做吗,是否是错误的模式,或者我应该如何解决?

go interface
1个回答
3
投票

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

类似:

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)
}
© www.soinside.com 2019 - 2024. All rights reserved.