【发布时间】:2018-08-02 14:42:39
【问题描述】:
我有一个应用程序,它具有相同 API 的多个并发实现(例如,一个由 SQL 数据库支持,另一个由存储在 XML 文件中的数据集支持)。我真正想做的是为 API 中的每种类型的事物定义一个父类型
保存所有实现通用的成员变量,并且
定义了所有实现必须具有的方法。
所以,在(无效的)Go 中,我想做类似的事情:
type Person interface {
Name string
Title string
Position string
Boss() *Person
}
type Person_XML struct {
Person
}
func (p *Person_XML) Boss() (*Person, error) {
// Poke around an XML document and answer the question
return boss, nil
}
type Person_SQL {
Person
}
func (p *Person_SQL) Boss() (*Person, error) {
// Do a DB query and construct the record for the boss
return boss, nil
}
但是,当然,这是不合法的,因为只有结构才有成员变量,只有接口才有成员函数。我可以只用这样的接口来做到这一点:
type Person interface {
Name() string
Title() string
Position() string
Boss() Person
}
type Person_XML struct {
NameValue string
TitleValue string
PositionValue string
Person
}
func (p *Person_XML) Name() string {
return p.NameValue
}
func (p *Person_XML) Title() string {
return p.TitleValue
}
func (p *Person_XML) Position() string {
return p.PositionValue
}
func (p *Person_XML) Boss() (Person, error) {
// Poke around an XML document and answer the question
return boss, nil
}
对于其他实现也是如此。有没有不强迫我将成员变量转换为成员函数的替代方法?这种用例的最佳做法是什么?
【问题讨论】:
标签: go struct interface dry embedding