go【第七篇】接口

接口:说白了就是模拟多态

Go 语言提供了另外一种数据类型即接口,它把所有的具有共性的方法定义在一起,任何其他类型只要实现了这些方法就是实现了这个接口。

接口的定义和实现

示例一

package main

import (
	"fmt"
)

//定义一个接口
type Phone interface {
	call()
}

//定义一个对象和对象方法
type NokiaPhone struct {
}

func (nokiaPhone NokiaPhone) call() {
	fmt.Println("I am Nokia, I can call you!")
}

//定义一个对象和对象方法
type IPhone struct {
}

func (iPhone IPhone) call() {
	fmt.Println("I am iPhone, I can call you!")
}

func main() {
	var phone Phone
	//接口绑定对象
	phone = new(NokiaPhone)
	//接口实现
	phone.call()

	phone = new(IPhone)
	phone.call()

}
#########
I am Nokia, I can call you!
I am iPhone, I can call you!

示例二

mock的Get方法返回url,real的Get方法打印html网页程序

package main

import (
    "fmt"
    "x2oo6q/test/real"
    "x2oo6q/test/mock"
)

type Retriever interface {
    Get(url string) string
}

func download(r Retriever) string {
    return r.Get("http://www.imooc.com")
}

func main() {
    var r Retriever
    //接口绑定对象
    mockRetriever := mock.Retriever{
        Contents: "this is a fake imooc.com of mock"}
    r = &mockRetriever
    //接口实现
    fmt.Println(download(r))

    realRetriever := real.Retriever{}
    r = &realRetriever
    fmt.Println(download(r))

}
main.go
package mock

type Retriever struct {
    Contents string
}

func (r *Retriever) Get(url string) string {
    return r.Contents
}
mock.go
package real

import (
    "net/http"
    "net/http/httputil"
    "time"
)

type Retriever struct {
    UserAgent string
    TimeOut   time.Duration
}

func (r *Retriever) Get(url string) string {
    resp, err := http.Get(url)
    if err != nil {
        panic(err)
    }

    result, err := httputil.DumpResponse(
        resp, true)

    resp.Body.Close()

    if err != nil {
        panic(err)
    }

    return string(result)
}
real.go

 

 

  

 

posted @ 2018-02-05 15:37  沐风先生  阅读(124)  评论(0编辑  收藏  举报