dongpi2503 2017-08-31 21:28
浏览 13
已采纳

去和面向对象的范例

Given the following interface...

type Person struct {
    name, gender string
}

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

... and the following Male and Female implementations:

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())
}

As only Create is gender-specific, is there a way to let Male and Female inherit a common implementation of methods GetName and GetGender?

  • 写回答

1条回答 默认 最新

  • doudang2537 2017-08-31 21:45
    关注

    Embed Person in the Male and Female types and push the base methods up to 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(), "
    ", c.SayHello())
        c = CreateFemale("Jane")
        fmt.Println(c.GetName(), c.GetGender(), "
    ", c.SayHello())
    }
    

    See full example here: https://play.golang.org/p/GZcG-n_YpM

    This uses the interface Citizen instead of the type Person in the assignment, so let me know if that isn't what you are looking for.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 怎么解决这种情况,求解
  • ¥15 cadence PEX
  • ¥15 phython创建了文件 显示在项目下面,但运行不了,运行时还是运行main文件,并且说main文件不允许并行运行
  • ¥20 C++哈希表的设计构造哈希表
  • ¥15 FutureWarning:不推荐使用空或全 NA 条目的 DataFrame 串联行为。怎么改呢?
  • ¥15 Chatgpt突然无法正常显示数学公式,如何解决?
  • ¥15 一个用华为模拟器做的实验。
  • ¥28 opencv Cuda C++编译
  • ¥15 插入sim卡4g模组反复断连
  • ¥100 如何把 16bit Bayer 图像数据转换为 TIFF RGB