我會盡力在這里解釋我的情況。所以,我正在為我的應用程序創建一個 DAL。它同時訪問redis和mysql。redis接口如下:文件 NoSqlDBClient.go:type NosqlDb interface { HGet() string}type NosqlClient struct { key string}func GetNosqlClient() *NosqlClient{ return &NosqlClient{}}func (ns *NosqlClient) HGet()string {//actual implemenation would be different return ns.key}文件 SqldbClient.go:type SqlDB interface { ExecQuery()}type SqlClient struct { query string}func GetsqlClient() *SqlClient{ return &SqlClient{}}func (s *SqlClient) ExecQuery()string { //actual implemenation would be different return s.query}現在我需要實現一個 DBClient Factory,它維護一個 dbtype 和客戶端的映射。它是這樣的文件 DBClientFactory.gotype DBClientfactory struct { clientmap[string] //what data type to use???}func GetNoSqlDBClient() NosqlDb{ client:=NoSqlDBClient.GetNosqlClient() clientmap['nosql'] = client return client}func GetSqlDBClient() SqlDB{ client:=SqlDBClient.GetsqlClient() clientmap['sql'] = client return client}問題是如何在一張地圖中容納不同類型的客戶?我想定義另一個接口DBFactory,其中嵌入了其他兩個接口。但這顯然行不通,因為所有方法都不是由單個接口實現的。我該如何解決這個問題?
1 回答

智慧大石
TA貢獻1946條經驗 獲得超3個贊
您可以使用interface{}map 值類型,但是您會失去類型安全性,并且必須使用類型斷言或類型切換。
相反,您應該使用 2 種不同的地圖類型,一種用于您要存儲的每個接口:
type DBClientfactory struct {
nosqldbs map[string]NosqlDb
sqldbs map[string]SqlDB
}
并且每個函數或方法將使用適當的映射,GetNoSqlDBClient()將使用DBClientfactory.nosqldbs,GetSqlDBClient()并將使用DBClientfactory.sqldbs。
如果每個客戶端只有一個實例,則根本不要使用地圖,只需使用簡單的字段:
type DBClientfactory struct {
nosqldb NosqlDb
sqldb SqlDB
}
- 1 回答
- 0 關注
- 157 瀏覽
添加回答
舉報
0/150
提交
取消