【发布时间】:2016-12-29 22:27:13
【问题描述】:
package main
import "fmt"
type Pet interface {
Bark()
}
type Dog int
func (d Dog) Bark() {
fmt.Println("W! W! W!")
}
type Cat int
func (c Cat) Bark() {
fmt.Println("M! M! M!")
}
type AdoptFunc func(pet Pet)
func adoptDog(dog Dog) {
fmt.Println("You live in my house from now on!")
}
func adoptCat(cat Cat) {
fmt.Println("You live in my house from now on!")
}
func main() {
var adoptFuncs map[string]AdoptFunc
adoptFuncs["dog"] = adoptDog // cannot use adoptDog (type func(Dog)) as type AdoptFunc in assignment
adoptFuncs["cat"] = adoptCat // the same as above
}
如上面的代码,有没有办法用map或者array来收集一堆类似的函数adoptXxx?如果不是,那么在这种情况下使用什么模式是正确的?
【问题讨论】:
-
使
adoptCat接受Pet而不是Cat。一般来说:忘记继承和经典的 OOP 并重新设计。恕我直言,宠物、猫和狗是不好的例子。
标签: go interface generic-programming