首页 > 解决方案 > 同一方法的多个实现可能与 Go 和接口有不同的依赖关系

问题描述

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

我有一个 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 WSInterfaceCompute()接口定义中,并将其添加到添加中,即使它不需要它。

我将结束:

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
}

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

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

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

标签: gointerface

解决方案


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

就像是:

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)
}

推荐阅读