Object-oriented programming(OOP) in Golang
在OOP中,有三個重要的概念:封裝(Encapsulation)、繼承(Inheritance) 和 多型(Polymorphism)
封裝(Encapsulation)
封裝是指把數據和方法封裝到一個對象中,防止外界直接訪問對象的內部狀態。封裝可以提高代碼的安全性和可維護性,讓代碼更容易被理解和重用。 在OOP中,通常使用private、protected、public等訪問修飾符來實現封裝。 外部只能通過公共接口(方法)來訪問和修改這些內部資料。這樣做可以隱藏內部實現的細節,提高程式碼的可維護性和可重用性。例如:
type Person struct {
Name string
Age int
}
func (p *Person) SayHello() {
fmt.Printf("Hello, my name is %s and I'm %d years old.\n", p.Name, p.Age)
}
上面的代碼定義了一個名為Person的類,它有兩個屬性Name和Age,以及一個Publich Function SayHello。這
個方法可以訪問並顯示這個對象的Name和Age屬性。
繼承(Inheritance)
繼承(Inheritance)是指一個類可以繼承另一個類的屬性和方法,從而擴展或修改其功能。繼承可以實現程式設計中的抽象和重用。例如:
type Student struct {
Person
Grade int
}
func (s *Student) SayHello() {
fmt.Printf("Hello, my name is %s and I'm %d years old. I'm in grade %d.\n", s.Name, s.Age, s.Grade)
}
上面的代碼定義了一個名為Student的類,它繼承了Person類的屬性和方法,並添加了一個Grade屬性。同時,它還重寫了SayHello方法,以顯示學生的年齡和年級。
多型(Polymorphism)
多型是指同一種操作,對不同的對象會有不同的行為。 在OOP中,通常使用方法的重載(overloading)和方法的覆蓋(overriding)來實現多型。
package main
import "fmt"
// Shape 是一個圖形接口
type Shape interface {
Area() float64
}
// Square 是一個正方形類別
type Square struct {
side float64
}
// Area 是Square的一個方法,用於計算面積
func (s Square) Area() float64 {
return s.side * s.side
}
// Circle 是一個圓形類別
type Circle struct {
radius float64
}
// Area 是Circle的一個方法,用於計算面積
func (c Circle) Area() float64 {
return 3.14 * c.radius * c.radius
}
func main() {
// 創建一個正方形對象
s := Square{side: 5}
// 調用Area方法,計算面積
fmt.Println(s.Area()) // 55
// 創建一個圓形對象
c := Circle{radius: 2}
// 調用Area方法,計算面積
fmt.Println(c.Area()) // 12.56
// 定義一個Shape類型的變量
var shape Shape
// 將Square對象賦值給Shape變量
shape = s
// 調用Area方法,計算面積
fmt.Println(shape.Area()) // 25
// 將Circle對象賦值給Shape變量
shape = c
// 調用Area方法,計算面積
fmt.Println(shape.Area()) // 12.56
}
定義了一個圖形接口Shape,並讓正方形類別Square和圓形類別Circle實現了這個接口的方法Area。 然後,我們創建了正方形對象s和圓形對象c,並分別調用了它們的Area方法,計算面積。 接著,我們定義了一個Shape類型的變量shape,並將正方形對象s和圓形對象c分別賦值給它, 最後再次調用了它的Area方法,這時shape的實際類型是根據賦值的對象而變化的,從而實現了多型。