Go語言的面向對象學習

現在假設有這麼一個場景,你定義了一個struct叫做長方形,你現在想要計算他的面積,那麼按照我們一般的思路應該會用下面的方式來實現


package main
import "fmt"

type Rectangle struct {
 width, height float64
}

func area(r Rectangle) float64 {
 return r.width*r.height
}

func main() {
 r1 := Rectangle{12, 2}
 r2 := Rectangle{9, 4}
 fmt.Println("Area of r1 is: ", area(r1))
 fmt.Println("Area of r2 is: ", area(r2))
}


這個代碼是可以計算出來長方形的面積,但是area不是作為Rectangle的一個方法(類似面向對象裡面的方法)實現的, 而是Rectangle的對象(r1,r2)作為函數的一個參數傳入,然後計算獲取的。
這樣實現有什麼問題,當然沒有問題咯,但是當你代碼裡面增加一個圓形、正方形、多邊形等的時候,然後你又想計算他們的面積的時候怎麼辦啊?那就增加新的函數咯,但是函數名你就必須要跟著換了,你就要把函數名變成area_rectangle, area_circle, area_triangle...
這樣的實現不是最優雅的,而且從概念上來說一個形狀的面積應該是屬於它的一個特性,應該是屬於這個形狀的,就像他的字段一樣。
基於上面的原因所以就有了method的概念,method是附屬在一個給定的類型上的,他的語法和函數的申明語法幾乎一樣,除了在func後面跟一個receiver(也就是給定的類型)
用Rob Pike的話來說就是:[indent]

“A method is a function with an implicit first argument, called a receiver.“


method的語法如下:

func (ReceiverType r) func_name (parameters) (results)


下面我們用最開始的例子用method來實現:

package main
import (
 "fmt"
 "math"
)

type Rectangle struct {
 width, height float64
}

type Circle struct {
 radius float64
}

func (r Rectangle) area() float64 {
 return r.width*r.height
}

func (c Circle) area() float64 {
 return c.radius * c.radius * math.Pi
}


func main() {
 r1 := Rectangle{12, 2}
 r2 := Rectangle{9, 4}
 c1 := Circle{10}
 c2 := Circle{25}

 fmt.Println("Area of r1 is: ", r1.area())
 fmt.Println("Area of r2 is: ", r2.area())
 fmt.Println("Area of c1 is: ", c1.area())
 fmt.Println("Area of c2 is: ", c2.area())
}


在使用method的時候重要注意幾點

  • 雖然method的名字一模一樣,但是如果接收者不一樣,那麼method就不一樣
  • method裡面可以訪問接收者的字段
  • 調用method通過.訪問,就像struct裡面訪問字段一樣

那是不是method只能作用在struct上面呢?當然不是咯,他可以定義在任何你自定義的類型、內置類型、struct等各種類型上 面。這裡你是不是有點迷糊了,什麼叫自定義類型,自定義類型不就是struct嘛,不是這樣的哦,struct只是自定義類型裡面一種比較特殊的類型而 已,還有其他自定義類型申明,可以通過如下這樣的申明來實現。

type type_name type_literal


請看下面這個申明自定義類型的代碼

type ages int

type money float32

type months map[string]int

m := months {
 "January":31,
 "February":28,
 ...
 "December":31,
} 


看到了嗎?簡單的很吧,這樣你就可以在自己的代碼裡面定義有意義的類型了,實際上只是一個定義了一個別名,有點類似於c中的typedef,例如上面ages替代了int
好了,讓我們回到method


你可以在任何的自定義類型中定義任意多的method,接下來讓我們看一個複雜一點的例子

package main
import "fmt"

const(
 WHITE = iota
 BLACK
 BLUE
 RED
 YELLOW
)

type Color byte

type Box struct {
 width, height, depth float64
 color Color
}

type BoxList []Box //a slice of boxes

func (b Box) Volume() float64 {
 return b.width * b.height * b.depth
}

func (b *Box) SetColor(c Color) {
 b.color = c
}

func (bl BoxList) BiggestsColor() Color {
 v := 0.00
 k := Color(WHITE)
 for _, b := range bl {
 if b.Volume() > v {
 v = b.Volume()
 k = b.color
 }
 }
 return k
}

func (bl BoxList) PaintItBlack() {
 for i, _ := range bl {
 bl[i].SetColor(BLACK)
 }
}

func (c Color) String() string {
 strings := []string {"WHITE", "BLACK", "BLUE", "RED", "YELLOW"}
 return strings[c]
}

func main() {
 boxes := BoxList {
 Box{4, 4, 4, RED},
 Box{10, 10, 1, YELLOW},
 Box{1, 1, 20, BLACK},
 Box{10, 10, 1, BLUE},
 Box{10, 30, 1, WHITE},
 Box{20, 20, 20, YELLOW},
 }

 fmt.Printf("We have %d boxes in our set\n", len(boxes))
 fmt.Println("The volume of the first one is", boxes[0].Volume(), "cm³")
 fmt.Println("The color of the last one is",boxes[len(boxes)-1].color.String())
 fmt.Println("The biggest one is", boxes.BiggestsColor().String())

 fmt.Println("Let's paint them all black")
 boxes.PaintItBlack()
 fmt.Println("The color of the second one is", boxes[1].color.String())

 fmt.Println("Obviously, now, the biggest one is", boxes.BiggestsColor().String())
}


上面這個例子我們通過const定義了一些常量,然後定義了一些自定義類型

  • Color作為byte的別名
  • 定義了一個struct:Box,含有三個長寬高字段和一個顏色屬性
  • 定義了一個slice:BoxList,含有Box

然後我們定義了一些method在這些類型上面

  • Volume()定義了接收者為Box,返回Box的容量

  • SetColor(c Color),把Box的顏色改為c
  • BiggestsColor()定在在BoxList上面,返回list裡面容量最大的顏色
  • PaintItBlack()把BoxList裡面所有Box的顏色全部變成黑色
  • String()定義在Color上面,返回真正的Color字符串

上面的代碼通過文字描述出來之後一看是不是很簡單?我們一般解決問題都是通過問題的描述,然後去用這樣的代碼實現。
指針作為receivers
現在讓我們回頭看看上面的SetColor的method,它的receiver是一個指向Box的指針,是的,你可以使用*Box。想想為啥要使用指針而不是Box本身呢?
我們先來看看我們上面SetColor的真正目的,我們是想改變這個Box的顏色,那麼如果我們是傳Box的指針,那麼我們接受的其實是Box的一個copy,如果改變了顏色值,其實是修改的copy,而不是真正的Box。所以我們需要傳入指針。
我們把receiver當作method的第一個參數來看,然後參考前面函數講解的傳值和傳引用
這個你也許會問了那SetColor函數里面應該這樣定義*b.Color=c,而不是b.Color=c,因為我們需要讀取到指針相應的值。


你是對的,其實Go裡面這兩種方式都是正確的,當你用指針去訪問相應的字段時(雖然指針沒有任何的字段),Go知道你要通過指針去獲取這個值,看到了吧,Go的設計是不是越來越吸引你了。
也許細心的讀者會問這樣的問題,PaintItBlack裡面調用SetColor的時候是不是應該寫成(&bl[i]).SetColor(BLACK),因為SetColor的receiver是*Box,而不是Box。
你又說對的,這兩種方式都可以,因為Go知道receiver是指針,他自動幫你轉了。
如果一個method的receiver是*T,你可以在一個T類型的變量V上面調用這個method,而不需要&V去調用這個method[/indent]
類似的[indent]
如果一個method的receiver是T,你可以在一個*T類型的變量P上面調用這個method,而不需要 *P去調用這個method[/indent]
所以,你不用擔心你是調用的指針的method還是不是指針的method,Go知道你要做的一切,這對於有多年C/C++編程經驗的同學來說,真是解決了一個很大的痛苦。
method繼承
前面一章我們學習了字段的繼承,那麼你也會發現Go的一個神奇之處,method也是可以繼承的。如果匿名字段實現了一個method,那麼包含這個匿名字段的strcut也能調用該method。讓我們來看下面這個例子

package main
import "fmt"

type Human struct {
 name string
 age int
 phone string
}

type Student struct {
 Human //匿名字段
 school string
}

type Employee struct {
 Human //匿名字段
 company string
}

//在human上面定義了一個method
func (h *Human) SayHi() {
 fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
}

func main() {
 mark := Student{Human{"Mark", 25, "222-222-YYYY"}, "MIT"}
 sam := Employee{Human{"Sam", 45, "111-888-XXXX"}, "Golang Inc"}

 mark.SayHi()
 sam.SayHi()
} 


method重載
上面的例子中,如果Emplyee想要實現自己的SayHi,怎麼辦?簡單,和匿名字段衝突一樣的道理,我們可以在Emplyee上面定義一個method,重載了匿名字段的方法。請看下面的例子

package main
import "fmt"

type Human struct {
 name string
 age int
 phone string
}

type Student struct {
 Human //匿名字段
 school string
}

type Employee struct {
 Human //匿名字段
 company string
}

//Human定義method
func (h *Human) SayHi() {
 fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
}

//Employee的method重載Human的method
func (e *Employee) SayHi() {
 fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", e.name,
 e.company, e.phone) //Yes you can split into 2 lines here.
}

func main() {
 mark := Student{Human{"Mark", 25, "222-222-YYYY"}, "MIT"}
 sam := Employee{Human{"Sam", 45, "111-888-XXXX"}, "Golang Inc"}

 mark.SayHi()
 sam.SayHi()
}


分享到:


相關文章: