golang 使用组合的方式实现继承 - Go语言中文社区

golang 使用组合的方式实现继承


摘要

golang并非完全面向对象的程序语言,为了实现面向对象的继承这一神奇的功能,golang允许struct间使用匿名引入的方式实现对象属性方法的组合

组合使用注意项

  • 使用匿名引入的方式来组合其他struct
  • 默认优先调用外层方法
  • 可以指定匿名struct以调用内层方法

代码事例

package main

import (
    "fmt"
)

type People struct{}

type People2 struct{}

func (p *People) ShowA() {
    fmt.Println("showA")
    p.ShowB()
}
func (p *People) ShowB() {
    fmt.Println("showB")
}

func (p *People) ShowC() {
    fmt.Println("showC")
}

func (p *People) ShowD() {
    fmt.Println("People:showD")
}

func (p *People2) ShowD() {
    fmt.Println("People2:showD")
}

type Teacher struct {
    People  //组合People
    People2 //组合People2
}

func (t *Teacher) ShowB() {
    fmt.Println("teacher showB")
}
func (t *Teacher) ShowC(arg string) {
    fmt.Println(arg)
}

func main() {
    t := Teacher{}

    //print showA
    //print showB
    t.ShowA()

    //print teacher showB
    t.ShowB()

    //print showB
    t.People.ShowB()

    //print test
    t.ShowC("test")

    //print showC
    t.People.ShowC()

    //因为组合方法中多次包含ShowD,所以调用时必须显示指定匿名方法
    //print People2:showD
    t.People2.ShowD()
}

版权声明:本文来源简书,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://www.jianshu.com/p/e70c3742404e
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-01-09 22:25:36
  • 阅读 ( 855 )
  • 分类:Go

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢