Golang中的依赖注入实践与探讨
Golang中的依赖注入实践与探讨 大家好,
我正在寻找一种合适的方法来注入依赖项。
假设我有以下代码,其中 FancyWrite 和 FancyRead 函数依赖于 WriteToFile 和 ReadFromFile 函数。由于这些函数会产生副作用,我希望能够注入它们,以便在测试中替换它们。
package main
func main() {
FancyWrite()
FancyRead()
}
////////////////
func FancyWrite() {
WriteToFile([]byte("content..."))
}
func FancyRead() {
ReadFromFile("/path/to/file")
}
////////////////
func WriteToFile(content []byte) (bool, error) {
return true, nil
}
func ReadFromFile(file string) ([]byte, error) {
return []byte{}, nil
}
我尝试过的一种方法是直接将它们作为参数传入函数:
package main
func main() {
FancyWrite(WriteToFile)
FancyRead(ReadFromFile)
}
////////////////
func FancyWrite(writeToFile func(content []byte) (bool, error)) {
writeToFile([]byte("content..."))
}
func FancyRead(readFromFile func(file string) ([]byte, error)) {
readFromFile("/path/to/file")
}
////////////////
func WriteToFile(content []byte) (bool, error) {
return true, nil
}
func ReadFromFile(file string) ([]byte, error) {
return []byte{}, nil
}
实际上,这种方法效果很好,但我能预见到随着依赖项增多,维护会变得困难。我还尝试了类似下面的工厂模式,这样主函数就不必关心如何构建 FancyWrite 函数。但是,语法变得有点难以阅读,并且如果有更多函数,维护起来会很困难。
func FancyWriteFactory(writeToFile func(content []byte) (bool, error)) func() {
return func() {
FancyWrite(writeToFile)
}
}
接下来,我尝试将函数作为结构体的方法:
package main
func main() {
dfu := DefaultFileUtil{}
ffm := FancyFileModule{
FileUtil: &dfu,
}
ffm.FancyWrite()
ffm.FancyRead()
}
////////////////
type FileUtil interface {
WriteToFile(content []byte) (bool, error)
ReadFromFile(file string) ([]byte, error)
}
type FancyFileModule struct {
FileUtil
}
func (fm *FancyFileModule) FancyWrite() {
fm.FileUtil.WriteToFile([]byte("content..."))
}
func (fm *FancyFileModule) FancyRead() {
fm.FileUtil.ReadFromFile("/path/to/file")
}
////////////////
type DefaultFileUtil struct{}
func (fu *DefaultFileUtil) WriteToFile(content []byte) (bool, error) {
return true, nil
}
func (fu *DefaultFileUtil) ReadFromFile(file string) ([]byte, error) {
return []byte{}, nil
}
现在,这种方法实际上效果很好,也更清晰。然而,我担心我只是在生硬地将函数作为方法使用,感觉有点奇怪。我想我可以这样理解:当你有某种状态时,结构体是很好的选择,或许我可以把依赖项看作是一种状态?
这些就是我尝试过的方法。所以我的问题是,在这种情况下,当将函数作为方法的唯一原因是为了让它们在别处成为依赖项的集合时,进行依赖注入的正确方式是什么?
谢谢!
更多关于Golang中的依赖注入实践与探讨的实战教程也可以访问 https://www.itying.com/category-94-b0.html
2 回复


