2 回答

TA貢獻1785條經(jīng)驗 獲得超8個贊
您想要的看起來與功能選項模式非常相似。請記住,函數(shù)是 Go 中的一等公民,因此您可以通過函數(shù)(或struct帶有 " apply" 方法的函子)傳遞數(shù)據(jù)。
例如:
package main
import "fmt"
type do struct{}
type DoOption func(*do)
func Do(opts ...DoOption) {
do := do{}
for _, opt := range opts {
opt(&do)
} // "apply" the options
// use the values...
}
type Foo struct{ value string }
type Bar struct{ value string }
func WithFoo(x Foo) func(*do) {
return func(*do) { fmt.Println(x.value) }
}
func WithBar(x Bar) func(*do) {
return func(*do) { fmt.Println(x.value) }
}
type dependencyContainer struct {
foo Foo
bar Bar
}
func main() {
s := dependencyContainer{Foo{"foo"}, Bar{"bar"}}
Do(WithFoo(s.foo), WithBar(s.bar))
}
https://play.golang.org/p/48rCTwn1f9C
此外,許多人認為顯式依賴注入(即通過構(gòu)造函數(shù)公開所有依賴項,而不是將它們隱藏在消費者代碼中)會導(dǎo)致更好的可維護代碼。
- 2 回答
- 0 關(guān)注
- 128 瀏覽
添加回答
舉報