Go基础知识点(十四) | 青训营笔记

76 阅读1分钟

这是我参与「第五届青训营 」笔记创作活动的第16天.

golang接口和类型的关系:

1.一个类型可以实现多个接口;

2.一个接口可以被多个类型实现.(多态)

package main

import "fmt"

//一个类型可以实现多个接口

type M interface {
   playM()
}
type V interface {
   playV()
}
//定义一个mall_mobile结构体实现M和V接口
type small_mobile struct {
   name string
}

func (mol small_mobile) playM() {
   fmt.Println("playMusic:", mol.name)

}
func (mol small_mobile) playV() {
   fmt.Println("playVideo:", mol.name)
}

// 一个接口可以被多个类型实现
type Petan interface {
   eat()
}

// 定义一个cat结构体,实现Petan接口
type cat struct {
   name string
}

// 定义一个dog结构体,实现Petan接口
type dog struct {
   name string
}

func (c cat) eat() {
   fmt.Println("cat:eat", c.name)
}
func (d dog) eat() {
   fmt.Println("dog:eat", d.name)
}
func main() {
   mol := small_mobile{
      name: "vivo",
   }
   mol.playV()
   mol.playM()
   fmt.Println("---------------")
   c := cat{
      name: "kity",
   }
   c.eat()
   d := dog{
      name: "大黄",
   }
   d.eat()

   //真正的多态:

   var pet Petan
   pet = dog{name: "hi",}
   pet.eat()
   pet = cat{name: "hello",}
   pet.eat()
}

golang接口可以嵌套

golang通过接口实现OCP设计原则

面向对象的可复用设计的第一块基石,便是所谓的开闭原则(简称:OCP原则).虽然go不是面向对象语言,但是可以模拟这个原则,对扩展是开放的,对修改是关闭的.

golang 模拟OOP的属性和方法

golang没有面向对象的概念,也没有封装的概念,但是可以通过结构体和函数绑定来实现OOP的属性和方法等特性.接收者receiver的方法.

例如,设计一个People结构体,有name,age属性,有eat,sleep,work方法.

package main

import "fmt"

//设计一个People结构体,有name,age属性
type People struct {
   name string
   age  int
}
//People的eat()方法
func (peo People) eat() {
   fmt.Printf("%v:eat..\n", peo.name)
}
//People的sleep()方法
func (peo People) sleep() {
   fmt.Printf("%v:sleep...\n", peo.name)
}
//People的work()方法
func (peo People) work() {
   fmt.Printf("%v:work...\n", peo.name)
}
func main() {
   peo := People{
      name: "lisi",
      age:  23,
   }
   peo.eat()
   peo.sleep()
   peo.work()
}
image.png