Go和面向对象的范例

时间:2017-08-31 21:28:06

标签: go

给出以下界面......

type Person struct {
    name, gender string
}

type Citizen interface {
    Create(name string) Citizen
    GetName() string
    GetGender() String
    SayHello() String
}

...以及以下MaleFemale实施:

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仅针对性别问题,是否有办法让MaleFemale继承方法GetNameGetGender的常见实现?

1 个答案:

答案 0 :(得分:4)

PersonMale类型中嵌入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类型,所以如果这不是您要找的那样,请告诉我。