我认为
image
和
database/sql
以及它们如何与其他LIB合作,更具idomatic,但如果你真的需要实施这种设计,我想出了一些hack-y。
诀窍是,golang可以在声明全局变量期间进行函数调用,而这发生在调用任何
init
. 所以我们可以在这期间进行注册工作。
//vehicle.go
import (
"fmt"
)
var _ = register("3",4)
type constructor func() *Vehicle
var reg = make(map[string]consturctor)
func register(name string, cons) bool {
_,ok:=reg[name]
if ok {
return false
}
reg[name] = cons
return true
}
var chosen string
func init() {
//turn that map into a slice if you want
//Chose one "implentation" from the slice/map if you wish
for chosen = range reg {
break // Take the first, it is dirty, I know.
}
if Chosen=="" {
panic("No Implentation!")
}
}
func NewVehicle() *Vehicle {
return reg[chosen]()
}
func main() {
fmt.Println("Hello, playground")
}
//car.go
var carsucc = register("car",constructor(NewCar))
func init() {
if !carsucc {
panic("car: multiple implentation!")
}
//off course you can fail silently
}
func NewCar() Vehicle {
return &Car{}
}