第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Go 中實(shí)現(xiàn)依賴注入

如何在 Go 中實(shí)現(xiàn)依賴注入

Go
30秒到達(dá)戰(zhàn)場 2022-01-04 15:52:11
我正在將一個應(yīng)用程序從Play(Scala)移植到Go并想知道如何實(shí)現(xiàn)依賴注入。在 Scala 中,我使用了 cake 模式,而在 Scala 中,Go我實(shí)現(xiàn)了一個DAO接口以及一個 Mongo 的實(shí)現(xiàn)。下面是我如何嘗試實(shí)現(xiàn)一個模式,讓我DAO根據(jù)需要更改實(shí)現(xiàn)(例如測試、不同的數(shù)據(jù)庫等):1. entity.gopackage modelsimport (    "time"    "gopkg.in/mgo.v2/bson")type (    Entity struct {        Id        bson.ObjectId `json:"id,omitempty" bson:"_id,omitempty"`        CreatedAt time.Time     `json:"createdAt,omitempty" bson:"createdAt,omitempty"`        LastUpdate time.Time    `json:"lastUpdate,omitempty" bson:"lastUpdate,omitempty"`    })2. 用戶.gopackage modelsimport (    "time")type (    User struct {        Entity                  `bson:",inline"`        Name      string        `json:"name,omitempty" bson:"name,omitempty"`        BirthDate time.Time     `json:"birthDate,omitempty" bson:"birthDate,omitempty"`    })3. dao.gopackage persistencetype (    DAO interface {        Insert(entity interface{}) error        List(result interface{}, sort string) error        Find(id string, result interface{}) error        Update(id string, update interface{}) error        Remove(id string) error        Close()    }    daoFactory func() DAO)var (    New daoFactory)上面的代碼是 90% 的好......我只是在mongoDao.go方法Insert和Update編譯器強(qiáng)制我將輸入強(qiáng)制entity轉(zhuǎn)換為特定類型 ( *models.User) 方面存在問題,但這使我無法擁有DAO適用于所有類型的通用組件。我該如何解決這個問題?
查看完整描述

2 回答

?
德瑪西亞99

TA貢獻(xiàn)1770條經(jīng)驗(yàn) 獲得超3個贊

創(chuàng)建一個為實(shí)體結(jié)構(gòu)實(shí)現(xiàn)的接口怎么樣?


type Entitier interface {

    GetEntity() *Entity

}

該實(shí)現(xiàn)將簡單地返回一個指向自身的指針,您現(xiàn)在可以在DAO的Insert和Update方法中使用該指針。這還有一個額外的好處,就是讓您在 DAO 方法的聲明中更加具體。與其簡單地說明他們采用任意interface{}參數(shù)作為參數(shù),您現(xiàn)在可以說他們采用Entitier.


像這樣:


func (dao *mongoDAO) Update(id string, update Entitier) error

這是我的意思的最小完整示例:


http://play.golang.org/p/lpVs_61mfM


希望這能給你一些想法!您可能要調(diào)整的命名Entity/ Entitier/GetEntity風(fēng)格和清晰一旦你上的圖案來使用結(jié)算。


查看完整回答
反對 回復(fù) 2022-01-04
?
一只甜甜圈

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超5個贊

這種概括


DAO interface {

    Insert(entity interface{}) error

看起來很霸道 你們都*models.User為 mongo斷言


doc := entity.(*models.User)

并做


user := &models.User{}

userController.dao.Insert(user)

使用通用 DAO 接口時。為什么不更精確地定義接口?


DAO interface {

    Insert(entity *models.User) error


查看完整回答
反對 回復(fù) 2022-01-04
  • 2 回答
  • 0 關(guān)注
  • 236 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號