2 回答
TA貢獻(xiàn)1785條經(jīng)驗(yàn) 獲得超8個(gè)贊
您想要的看起來(lái)與功能選項(xiàng)模式非常相似。請(qǐng)記住,函數(shù)是 Go 中的一等公民,因此您可以通過(guò)函數(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
此外,許多人認(rèn)為顯式依賴(lài)注入(即通過(guò)構(gòu)造函數(shù)公開(kāi)所有依賴(lài)項(xiàng),而不是將它們隱藏在消費(fèi)者代碼中)會(huì)導(dǎo)致更好的可維護(hù)代碼。
- 2 回答
- 0 關(guān)注
- 138 瀏覽
添加回答
舉報(bào)
