我有一个程序,其中使用了多种类型的模块,但所有不同类型的模块共享某些方法。我正在尝试构建一个可以重用于不同类型模块的通用工厂,但是我错过了接口继承或者在Go中调用的东西。
这是我试图尽可能简化的一个例子:
有一个使用通用Module
接口的通用工厂:
package main
var (
modules []Module
)
type Module interface {
RegisterFlagSet()
GetName() (string)
}
type Factory struct {
instances []Module
}
func RegisterModules(modules []Module) {
modules = modules
}
func (f *Factory) registerFlagSets() {
for _,inst := range f.instances {
inst.RegisterFlagSet()
}
}
func (f *Factory) GetInstance(seek string)(Module) {
for _,inst := range f.instances {
if (inst.GetName() == seek) {
return inst
}
}
panic("cannot find module")
}
然后是模块类型Timer
的更具体的实现。我试图尽可能多地重复使用工厂:
package main
import (
"time"
)
var (
timer_modules = []Timer{
// list all the timer modules here
}
)
type Timer interface {
Module
GetTicker() (*time.Ticker)
}
type TimerFactory struct {
Factory
}
func NewTimerFactory() TimerFactory {
tfact := TimerFactory{}
RegisterModules(timer_modules)
return tfact
}
当我尝试构建时,我收到此错误:
timer_factory.go:25: cannot use timer_modules (type []Timer) as type []Module in argument to RegisterModules
我不明白为什么type []Timer
的变量不能用作type []Module
,因为接口Module
的所有方法也都在接口Timer
中,那么它们应该兼容还是不兼容?有没有办法让它们兼容?
答案 0 :(得分:1)
https://golang.org/doc/faq#convert_slice_of_interface给出了解释。 其中一个解决方法是实现一个新的寄存器功能:
func RegisterModule(m Module) {
modules = append(modules, m)
}
并以两行为代价调用范围内的函数:
func NewTimerFactory() TimerFactory {
tfact := TimerFactory{}
for _, t := range timer_modules {
RegisterModule(t)
}
return tfact
}
答案 1 :(得分:0)
更改您的Timer声明
type Timer interface {
Module
GetTicker()(*time.Ticker)
}