【Go语言】面向对象扩展——接口

From:https://www.cnblogs.com/Mike-zh/p/3787679.html

简单地说 Interface是一组Method的组合,可以通过Interface来定义对象的一组行为。

如果某个对象实现了某个接口的所有方法,就表示它实现了该借口,无需显式地在该类型上添加接口说明。

Interface是一个方法的集合,它里面没有其他类型变量,而且Method只用定义原型 不用实现

①接口定义

1.命名时习惯以"er"结尾,如Printer Reader Writer

2.一个Interface的Method不宜过多,一般0~3个

3.一个Interface可以被任意的对象事项;相应地,一个对象也可以实现多个Interface

示例:

type Peoplestruct{

    Name string}

type Student struct{

    People

    School string}

type Teacher struct{

    People

    Department string}

func (p People) SayHi(){}

func (s Student) SayHi(){}

func (t Teacher) SayHi(){}

func (s Student) Study(){}//根据struct的方法提取接口 从而使struct自动实现了该接口type Speakerinterface{

    SayHi()

}

type Learner interface{

    SayHi()

    Study()

}


上面的例子中,Speaker接口被对象People,Teacher,Student实现;而Student同时实现了接口Speaker和Learner。

接口组合:

type SpeakLearnerinterface {

    Speaker

    Learner

}//组合后使得SpeakLearner具有Speaker和Learner的功能


空接口:

任何类型都实现了空接口,相当于Java中的Object类

func test(ainterface{}){}//该方法可以接受任意类型(int rune float32 struct...)的参数


②接口执行机制和接口赋值

首先介绍一种Go语言带接收者(Receiver)的函数机制(下面的两种情况执行结果一样,涉及到struct成员值改变时仍然一样)

情况1:

package main

import (

    "fmt")

type People struct {

    Name string}

func (p People) SayHi(){ //此处的Receiver是strcutfmt.Println("hello, this is", p.Name)

}

func (p *People) Study(){//此处的Receiver是****structfmt.Printf("%s is studying\n", p.Name)

}

type SpeakLearner interface {

    SayHi()

    Study()

}

func main() {

    people := People{"zhangsan"}//这里的people为People类型    people.SayHi()

    people.Study()

}


情况2:

func main() {

    people := &People{"zhangsan"}//这里的people为**People类型,即指针    people.SayHi()

    people.Study()

}


通过上面的例子可以看出Receiver为People和*People的函数均可被People或者*People两种类型调用,接下来借可能有在调用过程中People与*People之间的转换问题

看下面的例子:

package main

import (

    "fmt")

type Example struct{

    Integer1 int    Integer2 int}

func (e Example) Assign(num1 int, num2int) {

    e.Integer1, e.Integer2 = num1, num2

}

func (e *Example) Add(num1int, num2int) {

    e.Integer1 +=num1

    e.Integer2 +=num2

}

func main(){

    vare1 Example = Example{3,4}

    e1.Assign(1,1)

    fmt.Println(e1)

    e1.Add(1,1)

    fmt.Println(e1)

    vare2 *Example = &Example{3,4}

    e2.Assign(1,1)

    fmt.Println(e2)

    e2.Add(1,1)

    fmt.Println(e2)

}


以上程序的执行结果为:

{3,4}

{4,5}&{3,4}&{4,5}


可以看出实际执行的过程按函数定义前的Receiver类型执行。

对于接口的执行机制:

1.T仅拥有属于T类型的方法集,而*T则同时拥有(T+*T)方法集

2.基于T实现方法,表示同时实现了interface和interface(*T)接口

3.基于*T实现方法,那就只能是对interface(*T)实现接口

type Integerintfunc (a Integer) Less(b Integer) bool {

    returna < b

}

func (a *Integer) Add(b Integer) {

    *a += b

}

相应地,我们定义接口LessAdder,如下:

type LessAdder interface {

    Less(b Integer) bool    Add(b Integer)

}

现在有个问题:假设我们定义一个Integer类型的对象实例,怎么将其赋值给LessAdder接口呢?

应该用下面的语句(1),还是语句(2)呢?vara Integer =1varb LessAdder = &a  ... (1)varb LessAdder = a  ... (2)

答案是应该用语句(1)。原因在于,Go语言可以根据下面的函数:

func (a Integer) Less(b Integer) bool 

即自动生成一个新的Less()方法:

func (a *Integer) Less(b Integer)bool {

    return(*a).Less(b)

}

这样,类型*Integer就既存在Less()方法,也存在Add()方法,满足LessAdder接口。

而从另一方面来说,根据

func (a *Integer) Add(b Integer)

这个函数无法自动生成以下这个成员方法:

func (a Integer) Add(b Integer) {

    (&a).Add(b)

}

因为(&a).Add()改变的只是函数参数a,对外部实际要操作的对象并无影响,这不符合用

户的预期。所以,Go语言不会自动为其生成该函数。

因此,类型Integer只存在Less()方法,缺少Add()方法,不满足LessAdder接口,故此上面的语句(2)不能赋值。


接口赋值举例:

package main

import(

    "fmt")//定义对象People、Teacher和Studenttype Peoplestruct {

    Name string}

type Teacher struct{

    People

    Department string}

type Student struct{

    People

    School string}//对象方法实现func (p People) SayHi() {

    fmt.Printf("Hi, I'm %s. Nice to meet you!\n",p.Name)

}

func (t Teacher) SayHi(){

    fmt.Printf("Hi, my name is %s. I'm working in %s .\n", t.Name, t.Department)

}

func (s Student) SayHi() {

    fmt.Printf("Hi, my name is %s. I'm studying in %s.\n", s.Name, s.School)

}

func (s Student) Study() {

    fmt.Printf("I'm learning Golang in %s.\n", s.School)

}//定义接口Speaker和Learnertype Speakerinterface{

    SayHi()

}

type Learner interface{

    SayHi()

    Study()

}

func main() {

    people := People{"张三"}

    teacher := Teacher{People{"郑智"},"Computer Science"}

    student := Student{People{"李明"},"Yale University"}

    varisSpeaker//定义Speaker接口类型的变量is= people//is能存储Peopleis.SayHi()

    is= teacher//is能存储Teacheris.SayHi()

    is= student

    is.SayHi()//is能存储Studentvar il Learner

    il = student//Learner类型接口的变量能存储Student    il.Study()

}


执行结果为:

Hi, I'm 张三. Nice to meet you!Hi, my nameis郑智. I'm working in Computer Science .Hi, my nameis李明. I'm studying in Yale University.I'm learning Golang in Yale University.


通过这个例子可以 看到(如同Java等语言)接口机制在多态和创建可扩展可重用的代码时的重要作用

③匿名字段和接口转换

若果接口类型S内部嵌入了接口类型T(匿名),则接口匿名字段方法集规则如下:

1.如果S嵌入匿名类型T,则S方法集包含T方法集。

2.如果S嵌入匿名类型*T,则S方法集包含*T方法集(包括Riceiver为T和*T的方法)。

3.如果S嵌入匿名类型T或*T,则*S方法集包含*T方法集(包括Riceiver为T和*T的方法)。(重要)

例如:

package main

import(

    "fmt"   

)

type People struct {

    Name string}

type S1 struct{

    People              //S1类型嵌入匿名PeopleDepartmentstring}

type S2 struct{

    *People//S2类型嵌入匿名*PeopleDepartmentstring}

func (p People) Say1() {

    fmt.Printf("Hi, I'm %s. Say1111\n",p.Name)

}

func (p *People) Say2() {

    fmt.Printf("Hi, I'm %s. Say2222\n",p.Name)

}

type Speaker interface{

    Say1()

    Say2()

}

func main() {

    people := People{"张三"}

    s1 := S1{People{"郑智"},"Computer Science"}

    s2 := S2{&People{"李明"},"Math"}

    varis Speaker 

    is= &people//*People实现了Speaker接口is.Say1()

    is.Say2()

    //is = s1  //S1类型嵌入匿名People  不存在Say2()方法 因而未实现Speaker接口

            //错误提示: cannot use s1 (type S1) as type Speaker in assignment:

            //S1 does not implement Speaker (Say2 method has pointer receiver)is= s2//S2类型嵌入匿名*People  因而(p People) Say1()和(p *People) Say2()方法都有 实现了Speaker接口is.Say1()

    is.Say2()

    is= &s1//S1类型嵌入匿名People  *S1 实现了Speaker接口is.Say1()

    is.Say2()

    is= &s2//S2类型嵌入匿名*People  *S2 实现了Speaker接口is.Say1()

    is.Say2()

}


 执行结果为:

Hi, I'm 张三. Say1111Hi, I'm 张三. Say2222Hi, I'm 李明. Say1111Hi, I'm 李明. Say2222Hi, I'm 郑智. Say1111Hi, I'm 郑智. Say2222Hi, I'm 李明. Say1111Hi, I'm 李明. Say2222


从而证明了匿名字段方法集的3条规则。

接口转换类似于说是接口继承规则 可认为是实现复杂接口(方法多)向简单接口(方法少)转换,其中简单接口中的方法在复杂接口中均有声明 。例如:

package main

import(

    "fmt")

type People struct {

    Name string}

type Student struct{

    People

    School string}

func (p People) GetPeopleInfo() {

    fmt.Println(p)

}

func (s Student) GetStudentInfo() {

    fmt.Println(s)

}

type PeopleInfo interface{

    GetPeopleInfo()

}

type StudentInfo interface{

    GetPeopleInfo()

    GetStudentInfo()

}

func main() {

    varisStudentInfo = Student{People{"李明"},"Yele University"}

    is.GetStudentInfo()

    is.GetPeopleInfo()

    varip PeopleInfo =is    ip.GetPeopleInfo()

    ///ip.GetStudentInfo()  note:ip.GetStudentInfo undefined}


④接口类型推断:Comma-ok断言和Switch测试

 利用接口类型推断可以 反向知道接口类型变量里面实际保存的是哪一种类型的对象。

Go语言中,常用两种方法可以进行接口类型推断,即Comma-ok断言和Switch测试

Comma-ok断言使用格式如下

value,ok = element.(T)


用法示例:

//利用Comma-ok断言进行接口类型推断package main

import(

    "fmt")

type People struct{

    Name string    Age int}//定义空接口用于存储任意类型数据类型type Objectinterface{}

func main() {

    people := People{"张三",20}

    objs := make([]Object,4)

    objs[0], objs[1], objs[2], objs[3] =1,true,"Hello", people

    forindex, element := range objs{

        ifvalue, ok := element.(int); ok{

            fmt.Printf("objs[%d]类型是int,value=%d\n", index, value)

        }elseifvalue, ok := element.(bool); ok{

            fmt.Printf("objs[%d]类型是bool,value=%v\n", index, value)

        }elseifvalue, ok := element.(string); ok{

            fmt.Printf("objs[%d]类型是string,value=%s\n", index, value)

        }elseifvalue, ok := element.(People); ok{

            fmt.Printf("objs[%d]类型是Peole,value=%v\n", index, value)

        }else{

            fmt.Printf("objs[%d]类型未知\n", index)

        }

    }

}


结果是这样的:

objs[0]类型是int,value=1objs[1]类型是bool,value=trueobjs[2]类型是string,value=Hello

objs[3]类型是Peole,value={张三20}


使用Switch测试判断接口类型,程序结构更加简洁,示例如下(只修改了示例中的main函数):

func main() {

    people := People{"张三",20}

    objs := make([]Object,4)

    objs[0], objs[1], objs[2], objs[3] =1,true,"Hello", people

    forindex, element := range objs{


        switchvalue := element.(type){

        caseint:

            fmt.Printf("objs[%d]类型是int,value=%d\n", index, value)

        casebool:

            fmt.Printf("objs[%d]类型是bool,value=%v\n", index, value)

        casestring:

            fmt.Printf("objs[%d]类型是string,value=%s\n", index, value)

        case People:

            fmt.Printf("objs[%d]类型是Peole,value=%v\n", index, value)

        default:

            fmt.Printf("objs[%d]类型未知\n", index)

        }

    }

}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容