3 回答

TA貢獻1752條經驗 獲得超4個贊
是的,在 Go 中是可能的。
一個簡單的 Go 的三步 DI 系統:
假設您有一個包 A,它不應該導入包 B,而是調用該包中的一些函數;例如,函數 Load() 和 Save()。
在包 A 中,使用這些函數定義一個接口類型。
type Storage interface {
Load(string) []byte
Save(string, []byte)
}
然后,包 A 中的類型可以引用該接口并調用 Load() 和 Save(),而無需知道這些調用的實際接收者。
type StructA struct {
content []byte
storage Storage
}
func NewStructA(s Storage) *StructA {
return &StructA{
content: ...,
storage: s,
}
}
func (a *StructA) Save(name string) {
a.storage.Save(name, a.content)
}
func (a *StructA) Load(name string) {
a.content = a.storage.Load(name)
}
在包 B 中,實現 Load() 和 Save()。
type StoreB struct {
poem []byte
}
func (b *StoreB) Save(name string, contents []byte) {
// let's say StoreB contains a map called data
b.data[name] = contents
}
func (b *StoreB) Load(name string) []byte {
return b.data[name]
}
在包裝main中,連接電線。
storage := B.StructB
a := A.NewStructA(storage)
a.Save()
現在您可以添加其他存儲提供(包 C、D、...)并將它們連接到main.
storage2 := C.StructC
a2 := A.NewStructA(storage2)
a2.Save()
此處有更詳細的討論:https ://appliedgo.net/di/

TA貢獻1799條經驗 獲得超6個贊
- 3 回答
- 0 關注
- 138 瀏覽
添加回答
舉報