(三十四)golang--接口

不打扰是莪最后的温柔 提交于 2019-12-05 09:18:32

golang的多态特性主要体现在接口上;

主要优势:高内服低耦合;

package main

import (
    "fmt"
)

type usb interface {
    start()
    stop()
}

type phone struct {
}

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

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

type camera struct {
}

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

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

type computer struct {
}

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

func main() {
    computer := computer{}
    phone := phone{}
    camera := camera{}
    computer.working(phone)
    computer.working(camera)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!