接觸go快半年了, 但是還是屬于那種用到時去搜索的狀態(tài), 沒有系統(tǒng)的去研究研究
go 是一種強類型的語言,每當(dāng)我從php切換到go時總有些許的不適應(yīng),但是追求優(yōu)雅,就不應(yīng)該妥協(xié)。
go沒有 implements, extends 關(guān)鍵字,所以習(xí)慣于 OOP 編程,或許一開始會有點無所適從的感覺。 但go作為一種優(yōu)雅的語言, 給我們提供了另一種解決方案, 那就是鴨子類型:看起來像鴨子, 那么它就是鴨子.
那么什么是鴨子類型, 如何去實現(xiàn)呢 ?
接下來我會以一個簡單的例子來講述這種實現(xiàn)方案。
首先我們需要一個超類:
type Animal interface {
Sleep()
Age() int
Type() string
}
必然我們需要真正去實現(xiàn)這些的子類:
type Cat struct {
MaxAge int
}
func (this *Cat) Sleep() {
fmt.Println("Cat need sleep")
}
func (this *Cat) Age() int {
return this.MaxAge
}
func (this *Cat) Type() string {
return "Cat"
}
type Dog struct {
MaxAge int
}
func (this *Dog) Sleep() {
fmt.Println("Dog need sleep")
}
func (this *Dog) Age() int {
return this.MaxAge
}
func (this *Dog) Type() string {
return "Dog"
}
我們有兩個具體實現(xiàn)類 Cat, Dog, 但是Animal如何知道Cat, Dog已經(jīng)實現(xiàn)了它呢? 原因在于: Cat, Dog實現(xiàn)了Animal中的全部方法, 那么它就認(rèn)為這就是我的子類。
那么如何去使用這種關(guān)系呢?
func Factory(name string) Animal {
switch name {
case "dog":
return &Dog{MaxAge: 20}
case "cat":
return &Cat{MaxAge: 10}
default:
panic("No such animal")
}
}
我們使用具體工廠類來構(gòu)造具體的實現(xiàn)類, 在調(diào)用時你知道有這些方法, 但是并不清楚具體的實現(xiàn), 每一種類型的改變都不會影響到其它的類型。
package main
import (
"animals"
"fmt"
)
func main() {
animal := animals.Factory("dog")
animal.Sleep()
fmt.Printf("%s max age is: %d", animal.Type(), animal.Age())
}
來看看我們的輸出會是什么吧
> Output:
animals
command-line-arguments
Dog need sleep
Dog max age is: 20
> Elapsed: 0.366s
> Result: Success
這就是go中的多態(tài), 是不是比 implements/extends 顯示的表明關(guān)系更優(yōu)雅呢。