go - 同一方法的多个实现可能与 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 WSInterface
到Compute()
接口定义中,并将其添加到添加中,即使它不需要它。
我将结束:
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
}
但除此之外,它不会被使用。
在现实生活中,您可以对不同的微服务有多个依赖项,我发现定义不会在函数中使用的参数并不是那么优雅。这里一定有问题。
这样做可以吗,这是一个不好的模式,或者我应该如何解决它?
解决方案
这些特殊的接口/对象应该在构造函数中传递,保持接口本身干净。
就像是:
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)
}
推荐阅读
- bash - 如何将环境变量从字符串传递到 bash 命令
- firebase - 意外删除 Firebase 数据
- sql-server - 在 SQL Server 存储过程中将参数设置为“可选”
- tensorflow - 无法在 Ubuntu 16.04 中配置 tensorflow 以使用 GPU 加速
- arrays - 如何返回提供的数组中包含单个项目的所有项目的数组
- php - 限制 jpg 和 pdf 上传的文件大小
- reactjs - 为什么 req.query 总是空的?
- html - 为什么悬停在 flex 或 grid 中不起作用?
- python - 无法在 Docker alpine 映像中安装 Psycopg2
- kotlin - 微调器和切换按钮的中性状态