我会尽力在这里解释我的情况。所以,我正在为我的应用程序创建一个 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 关注
- 138 浏览
添加回答
举报
0/150
提交
取消