给出以下界面......
type Person struct {
name, gender string
}
type Citizen interface {
Create(name string) Citizen
GetName() string
GetGender() String
SayHello() String
}
...以及以下Male
和Female
实施:
type Male Person
func (m *Male) Create(name) Citizen {
return &Person{name, "male"}
}
func (m *Male) GetName() string {
return m.name
}
func (m *Male) GetGender() string {
return m.gender
}
func (m *Male) SayHello() string {
return "Hello (male voice)"
}
type Female Person
func (f *Female) Create(name) Citizen {
return &Person{name, "female"}
}
func (f *Female) GetName() string {
return f.name
}
func (f *Female) GetGender() string {
return f.gender
}
func (m *Female) SayHello() string {
return "Hello (female voice)"
}
func main() {
var p1 Person = &Male{}
var p2 Person = &Female{}
p1 = p1.Create("Joe")
p2 = p2.Create("Heidi")
log.Printf("%s is a %s",p1.GetName(), p1.GetGender())
log.Printf("%s says %s",p1.GetName(), p1.SayHello())
log.Printf("%s is a %s",p2.GetName(), p2.GetGender())
log.Printf("%s says %s",p2.GetName(), p2.SayHello())
}
由于Create
仅针对性别问题,是否有办法让Male
和Female
继承方法GetName
和GetGender
的常见实现?
答案 0 :(得分:4)
在Person
和Male
类型中嵌入Female
,并将基本方法推送至Person
。
type Male struct {
Person
}
type Female struct {
Person
}
func (m *Person) GetName() string {
return m.Name
}
func (m *Person) GetGender() string {
return m.Gender
}
func main() {
var c Citizen
c = CreateMale("Joe")
fmt.Println(c.GetName(), c.GetGender(), "\n", c.SayHello())
c = CreateFemale("Jane")
fmt.Println(c.GetName(), c.GetGender(), "\n", c.SayHello())
}
请参阅此处的完整示例:https://play.golang.org/p/GZcG-n_YpM
这在分配中使用界面Citizen
而不是Person
类型,所以如果这不是您要找的那样,请告诉我。