文章详情页 您现在的位置是:网站首页>文章详情

02.go笔记——go中的面向对象之"多态"

图片丢失 Jeyrce.Lu 发表于:2019年10月9日 19:51 分类:【Go 3094次阅读

接口

  • 接口解释:接口是一组行为规范的定义.

  • 接口中只能有方法声明,方法只能有名称、参数、返回值,不能有方法体

  • 每个接口中可以有多个方法声明,结构体把接口中 所有 方法都重写后,结构体就属于接口类型

  • Go语言中接口和结构体之间的关系是传统面向对象中is-like-a的关系

  • 定义接口类型关键字是interface

 type 接口名 interface{   
     方法名(参数列表) 返回值列表 
 }
  • 接口可以继承接口,且Go语言推荐把接口中方法拆分成多个接口

代码示例

  • 接口中声明完方法,结构体重写接口中方法后,编译器认为结构体实现了接口

    • 重写的方法要求必须和接口中方法名称、方法参数(参数名称可以不同)、返回值列表完全相同

 type People struct {  
     name string  
     age  int 
 }  
 
 type Live interface {  
     run(run int) 
 }  
 
 func (p *People) run(run int) {  
     fmt.Println(p.name, "正在跑步,跑了,", run, "米") 
 }  
 
 func main() {  
     peo := People{"张三", 17}  
     peo.run(100) 
 }
  • 如果接口中有多个方法声明,接口体必须重写接口中全部方法才任务结构体实现了接口

 type People struct {  
     name string  
     age  int 
 }  
 
 type Live interface {  
     run(run int)  eat() 
 }  
 
 func (p *People) run(run int) {  
     fmt.Println(p.name, "正在跑步,跑了,", run, "米") 
 } 
 
 func (p *People) eat() {  
     fmt.Println(p.name, "正在吃饭") 
 }  
 
 func main() {  
     peo := People{"张三", 17}  
     peo.run(100) 
 }
  • 接口可以继承接口(组合),上面代码可以改写成下面代码

 type People struct {  
     name string  
     age  int 
 }  
 
 type Live interface {  
     run(run int)  
     Eat 
 }  
 
 type Eat interface {  
     eat() 
 }  
 
 func (p *People) run(run int) {  
     fmt.Println(p.name, "正在跑步,跑了,", run, "米") 
 } 
 
 func (p *People) eat() {  
     fmt.Println(p.name, "正在吃饭") 
 }  
 
 func main() {  
     peo := People{"张三", 17}  
     peo.run(100) 
 }


多态

  • 多态:同一件事情由于条件不同产生的结果不同

  • 由于Go语言中结构体不能相互转换,所以没有结构体(父子结构体)的多态,只有基于接口的多态.这也符合Go语言对面向对象的诠释

  • 多态在代码层面最常见的一种方式是接口当作方法参数

代码示例

  • 结构体实现了接口的全部方法,就认为结构体属于接口类型,这是可以把结构体变量赋值给接口变量

  • 重写接口时接收者为Type*Type的区别

    • *Type可以调用*TypeType作为接收者的方法.所以只要接口中多个方法中至少出现一个使用*Type作为接收者进行重写的方法,就必须把结构体指针赋值给接口变量,否则编译报错

    • Type只能调用Type作为接收者的方法

 type Live interface {  
     run()  
     eat() 
 } 
 
 type People struct {  
     name string 
 }  
 
 func (p *People) run() {  
     fmt.Println(p.name, "正在跑步") 
 } 
 
 func (p People) eat() {  
     fmt.Println(p.name, "在吃饭") 
 }  
 
 func main() {  
     //重写接口时  
     var run Live = &People{"张三"}  
     run.run()  
     run.eat() 
 }
  • 既然接口可以接收实现接口所有方法的结构体变量,接口也就可以作为方法(函数)参数

 type Live interface {  
     run() 
 } 
 
 type People struct{} 
 
 type Animate struct{}  
 
 func (p *People) run() {  
     fmt.Println("人在跑") 
 } 
 
 func (a *Animate) run() {  
     fmt.Println("动物在跑") 
 }  
 
 func sport(live Live) {  
     fmt.Println(live.run) 
 }  
 
 func main() {  
     peo := &People{}  
     peo.run() //输出:人在跑  
     ani := &Animate{}  
     ani.run() //输出:动物在跑 
 }





版权声明 本文属于本站  原创作品,文章版权归本站及作者所有,请尊重作者的创作成果,转载、引用自觉附上本文永久地址: http://blog.lujianxin.com/x/art/c15psz4xp8fc

文章评论区

作者名片

图片丢失
  • 作者昵称:Jeyrce.Lu
  • 原创文章:61篇
  • 转载文章:3篇
  • 加入本站:1830天

站点信息

  • 运行天数:1831天
  • 累计访问:164169人次
  • 今日访问:0人次
  • 原创文章:69篇
  • 转载文章:4篇
  • 微信公众号:第一时间获取更新信息