Golang中實現依賴注入的方法有以下幾種:
type Foo struct {
Dependency *Dependency
}
func NewFoo(dependency *Dependency) *Foo {
return &Foo{
Dependency: dependency,
}
}
type Foo struct {
Dependency *Dependency
}
func (f *Foo) SetDependency(dependency *Dependency) {
f.Dependency = dependency
}
type Dependency interface {
Method()
}
type DependencyImpl struct {}
func (d *DependencyImpl) Method() {}
type Foo struct {
Dependency Dependency
}
func NewFoo(dependency Dependency) *Foo {
return &Foo{
Dependency: dependency,
}
}
type DependencyImpl struct {}
func (d *DependencyImpl) Method() {}
type Foo struct {
Dependency Dependency
}
func NewFoo() *Foo {
return &Foo{}
}
func main() {
container := di.NewContainer()
container.Register(&DependencyImpl{})
container.Register(func(dependency Dependency) *Foo {
return &Foo{
Dependency: dependency,
}
})
foo := container.Resolve((*Foo)(nil)).(*Foo)
}
以上是幾種常見的實現依賴注入的方法,根據具體的應用場景和需求可以選擇合適的方法。