适配器函数类型(http.HandlerFunc)

适配器函数类型(http.HandlerFunc)

适配器函数类型 #

适配器模式的核心是适配器函数类型(Adapter Function Type)。适配器函数类型是一个辅助水平组合实现的“工具”类型。这里我要再强调一下,它是一个类型。它可以将一个满足特定函数签名的普通函数,显式转换成自身类型的实例,转换后的实例同时也是某个接口类型的实现者。

最典型的适配器函数类型莫过于http.HandlerFunc了。这里,我们再来看一个应用 http.HandlerFunc 的例子:

func greetings(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Welcome!")
}

func main() {
    http.ListenAndServe(":8080", http.HandlerFunc(greetings))
}

这个例子通过 http.HandlerFunc 这个适配器函数类型,将普通函数 greetings 快速转化为满足 http.Handler 接口的类型。而 http.HandleFunc 这个适配器函数类型的定义是这样的:

// $GOROOT/src/net/http/server.go
func ListenAndServe(addr string, handler Handler) error

type Handler interface {
    ServeHTTP(ResponseWriter, *Request)
}

type HandlerFunc func(ResponseWriter, *Request)

func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
    f(w, r)
}

经过 HandlerFunc 的适配转化后,我们就可以将它的实例用作实参,传递给接收 http.Handler 接口的 http.ListenAndServe 函数,从而实现基于接口的组合。

Viewpoint #

From #

30|接口:Go中最强大的魔法