栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Go学习:接口的概念

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Go学习:接口的概念

强耦合 downloader
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	resp, err := http.Get("https://blog.csdn.net/qq_43135259/article/details/123293118?spm=1001.2014.3001.5502")
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	bytes, _ := ioutil.ReadAll(resp.Body)
	// ...
	fmt.Printf("%sn",bytes)
}

这种写法也能实现读出网页的源码,但是这种方法耦合性太强 低耦合 urlretriever

package infa

import (
	"io/ioutil"
	"net/http"
)

type Retriever struct {}

func(Retriever) Get(url string)string{
	resp, err := http.Get(url)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	bytes, _ := ioutil.ReadAll(resp.Body)
	return string(bytes)
}

Retriever
package testing

type Retriever struct {}

func (Retriever)Get(url string)string  {
	return "fake content"
}

downloader
package main

import (
	"fmt"
	infa "learngo/infra"
)

func getRetriever() infa.Retriever {
	return infa.Retriever{}
}

func main() {
	var retriever infa.Retriever = getRetriever()
	bytes := retriever.Get("https://blog.csdn.net/qq_43135259/article/details/123293118?spm=1001.2014.3001.5502")
	// ...
	fmt.Println(bytes)
}

这种相对于强耦合,耦合性降低了很多,但是retriever类型是有限制的,必须使用infa.Retriever;如果我们需要使用testing.Retriever的话代码就需要改动很大,改起来也会比较吃力 接口 downloader

package main

import (
	"fmt"
	"learngo/testing"
)

func getRetriever() retriever {
	return testing.Retriever{}
}

type retriever interface {
	Get(string)string
}

func main() {
	var retriever retriever = getRetriever()
	bytes := retriever.Get("https://blog.csdn.net/qq_43135259/article/details/123293118?spm=1001.2014.3001.5502")
	// fake content
	fmt.Println(bytes)
}

使用接口的话,我们使用Get方法需要使用infa.Retriever/testing.Retriever只需要改动getRetriever()函数内的返回值就可以了 duck typing


大黄鸭是鸭子吗?

传统类型系统: 脊索动物门,脊椎动物亚门…(不是鸭子)duck typing:是鸭子;

duck typing

像鸭子走路,像鸭子叫(长得像鸭子),那么就是鸭子描述事物的外部行为而非内部结构严格来说go属于结构化类型系统,类似duck typing,但不是duck typing python中的duck typing

	def download(retriever):
		return retriever.get("https://blog.csdn.net/qq_43135259/article/details/123293118?spm=1001.2014.3001.5502")

运行时才知道传入的 retriever有没有get通常需要注释来说明接口 c++中的duck typing

	template 
	string download(const R& retriever){
		return retriever.get("https://blog.csdn.net/qq_43135259/article/details/123293118?spm=1001.2014.3001.5502")
	}

编译时才知道传入的retriever有没有get方法通常需要注释来说明接口 java中的类似代码

    
    String download(R r) {
        return r.get("https://blog.csdn.net/qq_43135259/article/details/123293118?spm=1001.2014.3001.5502")
    }

传入的参数必须实现Retriever接口不是duck typing由于强制性实现,不需要注释来说明接口 go语言的duck typing

同时具有python,c++的duck typing的灵活性又具有java的类型检查

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/754888.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号