您的位置:首页 > 编程语言 > Go语言

(三十五)golang--面向对象之多态

2019-11-24 16:06 1481 查看

多态:变量具有多种形态,可以用统一的接口来调用不同的实现。

接口体现多态特征:

(1)多态参数:之前所讲的Usb接口案例,既可以接受手机变量,也可以接受相机变量,就体现了usb接口的多态;

(2)多态数组:

package main

import (
"fmt"
)

type usb interface {
start()
stop()
}

type phone struct {
name string
}

func (p phone) start() {
fmt.Println(p.name, "手机开始工作")
}

func (p phone) stop() {
fmt.Println(p.name, "手机停止工作")
}

type camera struct {
name string
}

func (c camera) start() {
fmt.Println(c.name, "相机开始工作")
}

func (c camera) stop() {
fmt.Println(c.name, "相机停止工作")
}

type computer struct {
}

func (co computer) working(usb usb) {
usb.start()
usb.stop()
}

func main() {
var usbArr [3]usb
usbArr[0] = phone{"小米"}
usbArr[1] = phone{"vivo"}
usbArr[2] = camera{"尼康"}
fmt.Println(usbArr)
for i := 0; i < len(usbArr); i++ {
usbArr[i].start()
usbArr[i].stop()
}
}

我们以前讲到,数组是只能存储同一种类型的数据,利用多态数组,就可以存储不同的类型了;

如何将一个接口变量赋值给一个自定义类型的变量?使用类型断言

类型断言:由于接口是一般类型,不知道具体类型,如果要转成具体类型,就需要使用类型断言;要保持原来空接口指向的数据类型和断言的数据类型一致;

为了避免输出panic报错,可以进行断言判断;

类型断言实践一:

我们给phone中加入一个方法call(),在调用usb变量时,usb.call(),肯定是不对的,因为usb可能是phone,也可能是camera,而camera是没有这个函数的,因此,在调用的时候用类型断言。

package main

import (
"fmt"
)

type usb interface {
start()
stop()
}

type phone struct {
name string
}

func (p phone) start() {
fmt.Println(p.name, "手机开始工作")
}

func (p phone) call() {
fmt.Println(p.name,"手机在打电话")
}

func (p phone) stop() {
fmt.Println(p.name, "手机停止工作")
}

type camera struct {
name string
}

func (c camera) start() {
fmt.Println(c.name, "相机开始工作")
}

func (c camera) stop() {
fmt.Println(c.name, "相机停止工作")
}

type computer struct {
}

func (co computer) working(usb usb) {
usb.start()
//如果usb还指向phone的结构体变量,则还需要调用call方法
if phone, ok := usb.(phone); ok {
phone.call()
}
usb.stop()
}

func main() {
var usbArr [3]usb
usbArr[0] = phone{"小米"}
usbArr[1] = phone{"vivo"}
usbArr[2] = camera{"尼康"}
var com computer
fmt.Println(usbArr)
for i := 0; i < len(usbArr); i++ {
com.working(usbArr[i])
}
}

类型断言实践2:循环判断输入参数的类型

package main

import (
"fmt"
)

type student struct {
name string
}

func typeJudge(items ...interface{}) {
for index, x := range items {
switch x.(type) {
case bool:
fmt.Printf("第%v个参数是bool类型,值是%v\n", index, x)
case int, int32, int64:
fmt.Printf("第%v个参数是整数类型,值是%v\n", index, x)
case float32:
fmt.Printf("第%v个参数是float32类型,值是%v\n", index, x)
case float64:
fmt.Printf("第%v个参数是float64类型,值是%v\n", index, x)
case string:
fmt.Printf("第%v个参数是string类型,值是%v\n", index, x)
case student:
fmt.Printf("第%v个参数是student类型,值是%v\n", index, x)
case *student:
fmt.Printf("第%v个参数是*student类型,值是%v\n", index, x)
default:
fmt.Printf("第%v个参数类型不确定,值是%v\n", index, x)
}
}
}

func main() {
var n1 float32 = 1.1
var n2 float64 = 1.2
var n3 int32 = 1
var name string = "tom"
var n5 bool = true

stu1 := student{"jack"}
stu2 := &student{"bob"}

typeJudge(n1, n2, n3, name, n5, stu1, stu2)
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: