第三章:抽象数据类型:Go 中的面向对象编程
3. 多态
在 Go 语言中,多态性主要通过接口来实现。接口定义了一组方法,而具体类型则通过实现这些方法来满足接口的要求。通过接口,我们可以编写更加通用和灵活的代码。
使用接口实现多态
我们将通过一个简单的例子来展示如何使用接口实现多态。假设我们有一个几何图形(Shape)接口,包含计算面积(Area)的方法。然后,我们将定义两个具体类型:矩形(Rectangle)和圆形(Circle),它们都实现了 Shape 接口。
示例:定义 Shape 接口
package shape
// Shape 接口,定义了一个计算面积的方法
type Shape interface {
Area() float64
}
示例:定义 Rectangle 类型
package shape
// Rectangle 结构体,表示矩形
type Rectangle struct {
Width, Height float64
}
// 实现 Shape 接口的 Area 方法
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
示例:定义 Circle 类型
package shape
import "math"
// Circle 结构体,表示圆形
type Circle struct {
Radius float64
}
// 实现 Shape 接口的 Area 方法
func (c Circle) Area() float64 {
return math.Pi * c.Radius * c.Radius
}
示例:使用多态
package main
import (
"fmt"
"project/shape" // 导入 shape 包
)
func printArea(s shape.Shape) {
fmt.Printf("Area: %.2f\n", s.Area())
}
func main() {
r := shape.Rectangle{Width: 10, Height: 5}
c := shape.Circle{Radius: 7}
printArea(r) // 输出矩形的面积
printArea(c) // 输出圆形的面积
}
在上述示例中,我们定义了一个 Shape 接口,它包含一个 Area 方法。然后,我们定义了 Rectangle 和 Circle 结构体,并分别实现了 Area 方法。通过多态,我们可以编写一个通用的 printArea 函数,该函数接收任何实现了 Shape 接口的类型,并输出其面积。
这种多态性使得代码更加灵活和可扩展。例如,如果我们需要添加一个新的几何图形,只需定义一个新的结构体并实现 Shape 接口,无需修改现有的代码。
通过以上示例,我们展示了如何在 Go 中使用接口实现多态。接口不仅提高了代码的可读性和可维护性,还使得我们可以编写更加通用和灵活的代码。